import os, json
import docx
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml import OxmlElement, parse_xml
from docx.oxml.ns import nsdecls, qn

with open('parsed_recipes.json', encoding='utf-8') as f:
    recipes = json.load(f)

print(f"Generating consolidated Word document for {len(recipes)} recipes...")

doc = docx.Document()

# Page setup: A4 with 0.5 inch margins
sections = doc.sections
for section in sections:
    section.top_margin = Inches(0.5)
    section.bottom_margin = Inches(0.5)
    section.left_margin = Inches(0.5)
    section.right_margin = Inches(0.5)
    section.page_width = Inches(8.27)
    section.page_height = Inches(11.69)

def set_cell_background(cell, fill_hex):
    shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{fill_hex}"/>')
    cell._tc.get_or_add_tcPr().append(shd)

def set_cell_margins(cell, top=80, bottom=80, left=120, right=120):
    tcPr = cell._tc.get_or_add_tcPr()
    tcMar = parse_xml(f'<w:tcMar {nsdecls("w")}><w:top w:w="{top}" w:type="dxa"/><w:bottom w:w="{bottom}" w:type="dxa"/><w:left w:w="{left}" w:type="dxa"/><w:right w:w="{right}" w:type="dxa"/></w:tcMar>')
    tcPr.append(tcMar)

def set_cell_borders(cell, color="CBD5E1", sz="4", val="single"):
    tcPr = cell._tc.get_or_add_tcPr()
    borders = parse_xml(f'''
        <w:tcBorders {nsdecls("w")}>
            <w:top w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:left w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:bottom w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
            <w:right w:val="{val}" w:sz="{sz}" w:space="0" w:color="{color}"/>
        </w:tcBorders>
    ''')
    tcPr.append(borders)

PREELABORADO_KEYWORDS = [
    'crema', 'yema', 'trufa', 'nata', 'gelatina', 'almíbar', 'almibar', 'glasa', 'glaseado',
    'praliné', 'praline', 'variegato', 'cobertura', 'masa madre', 'fondant', 'caramelo',
    'pasta de almendra', 'pasta de avellana', 'gianduja', 'preparado'
]

def is_preelaborado(recipe):
    name = recipe['name'].lower()
    fam = recipe['family'].lower()
    if 'cremas' in fam or 'nata' in fam or 'trufas' in fam or 'rellenos' in fam:
        return True
    for kw in PREELABORADO_KEYWORDS:
        if kw in name:
            return True
    return False

for r_idx, r in enumerate(recipes):
    preelab = is_preelaborado(r)
    
    # Header Table
    tbl_hdr = doc.add_table(rows=1, cols=2)
    tbl_hdr.alignment = WD_TABLE_ALIGNMENT.CENTER
    tbl_hdr.autofit = False
    
    cell_l = tbl_hdr.cell(0, 0)
    cell_l.width = Inches(5.2)
    set_cell_background(cell_l, "1A365D")
    set_cell_margins(cell_l, top=100, bottom=100, left=140, right=140)
    p_l = cell_l.paragraphs[0]
    p_l.alignment = WD_ALIGN_PARAGRAPH.LEFT
    p_l.paragraph_format.space_before = Pt(0)
    p_l.paragraph_format.space_after = Pt(0)
    run_l1 = p_l.add_run("RAÚL ASENCIO PASTELERÍAS\n")
    run_l1.font.name = "Arial"
    run_l1.font.size = Pt(13)
    run_l1.font.bold = True
    run_l1.font.color.rgb = RGBColor(255, 255, 255)
    run_l2 = p_l.add_run("FICHA TÉCNICA DE RECETA / FORMULACIÓN DE OBRADOR")
    run_l2.font.name = "Arial"
    run_l2.font.size = Pt(8.5)
    run_l2.font.color.rgb = RGBColor(226, 232, 240)
    
    cell_r = tbl_hdr.cell(0, 1)
    cell_r.width = Inches(2.07)
    set_cell_background(cell_r, "2D3748")
    set_cell_margins(cell_r, top=100, bottom=100, left=140, right=140)
    p_r = cell_r.paragraphs[0]
    p_r.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    p_r.paragraph_format.space_before = Pt(0)
    p_r.paragraph_format.space_after = Pt(0)
    run_r1 = p_r.add_run(f"RECETA Nº {r['num']}\n")
    run_r1.font.name = "Arial"
    run_r1.font.size = Pt(11)
    run_r1.font.bold = True
    run_r1.font.color.rgb = RGBColor(255, 255, 255)
    run_r2 = p_r.add_run(f"{r['family'][:25]}")
    run_r2.font.name = "Arial"
    run_r2.font.size = Pt(8)
    run_r2.font.color.rgb = RGBColor(203, 213, 225)
    
    p_space = doc.add_paragraph()
    p_space.paragraph_format.space_before = Pt(3)
    p_space.paragraph_format.space_after = Pt(3)
    
    # Meta Table (RECETA & PREELABORADO)
    tbl_meta = doc.add_table(rows=2, cols=2)
    tbl_meta.alignment = WD_TABLE_ALIGNMENT.CENTER
    tbl_meta.autofit = False
    
    # Row 0: Receta & Check
    c00 = tbl_meta.cell(0, 0)
    c00.width = Inches(4.5)
    set_cell_background(c00, "F1F5F9")
    set_cell_borders(c00, "CBD5E1")
    set_cell_margins(c00, top=90, bottom=90, left=120, right=120)
    p00 = c00.paragraphs[0]
    p00.paragraph_format.space_before = Pt(0)
    p00.paragraph_format.space_after = Pt(0)
    run_lbl = p00.add_run("RECETA: ")
    run_lbl.font.name = "Arial"
    run_lbl.font.bold = True
    run_lbl.font.size = Pt(10)
    run_lbl.font.color.rgb = RGBColor(30, 41, 59)
    run_val = p00.add_run(f"{r['name'].upper()}")
    run_val.font.name = "Arial"
    run_val.font.bold = True
    run_val.font.size = Pt(11)
    run_val.font.color.rgb = RGBColor(26, 54, 93)
    
    c01 = tbl_meta.cell(0, 1)
    c01.width = Inches(2.77)
    set_cell_background(c01, "FEFCBF" if preelab else "F1F5F9")
    set_cell_borders(c01, "CBD5E1")
    set_cell_margins(c01, top=90, bottom=90, left=120, right=120)
    p01 = c01.paragraphs[0]
    p01.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p01.paragraph_format.space_before = Pt(0)
    p01.paragraph_format.space_after = Pt(0)
    si_box = "☑ SÍ" if preelab else "☐ SÍ"
    no_box = "☑ NO" if not preelab else "☐ NO"
    run_chk = p01.add_run(f"¿ES PREELABORADO?   {si_box}     {no_box}")
    run_chk.font.name = "Arial"
    run_chk.font.bold = True
    run_chk.font.size = Pt(10)
    run_chk.font.color.rgb = RGBColor(15, 23, 42)
    
    # Row 1: Sub metadata
    c10 = tbl_meta.cell(1, 0)
    c10.width = Inches(4.5)
    set_cell_background(c10, "FAFAFA")
    set_cell_borders(c10, "CBD5E1")
    set_cell_margins(c10, top=60, bottom=60, left=120, right=120)
    p10 = c10.paragraphs[0]
    p10.paragraph_format.space_before = Pt(0)
    p10.paragraph_format.space_after = Pt(0)
    r10 = p10.add_run(f"FECHA REVISIÓN: 05/11/2026       RESPONSABLE: Obrador Raúl Asencio")
    r10.font.name = "Arial"
    r10.font.size = Pt(8.5)
    r10.font.color.rgb = RGBColor(100, 116, 139)
    
    c11 = tbl_meta.cell(1, 1)
    c11.width = Inches(2.77)
    set_cell_background(c11, "FAFAFA")
    set_cell_borders(c11, "CBD5E1")
    set_cell_margins(c11, top=60, bottom=60, left=120, right=120)
    p11 = c11.paragraphs[0]
    p11.paragraph_format.space_before = Pt(0)
    p11.paragraph_format.space_after = Pt(0)
    r11 = p11.add_run(f"FUENTE MANUSCRITO: {r['source']}")
    r11.font.name = "Arial"
    r11.font.size = Pt(8.5)
    r11.font.color.rgb = RGBColor(100, 116, 139)
    
    p_space2 = doc.add_paragraph()
    p_space2.paragraph_format.space_before = Pt(3)
    p_space2.paragraph_format.space_after = Pt(3)
    
    # Ingredients Table
    # Rows: 1 header + ingredients + empty rows if necessary
    total_rows = max(len(r['ingredients']) + 1, 12)
    tbl_ing = doc.add_table(rows=total_rows, cols=4)
    tbl_ing.alignment = WD_TABLE_ALIGNMENT.CENTER
    tbl_ing.autofit = False
    
    col_widths = [Inches(0.5), Inches(3.4), Inches(1.5), Inches(1.87)]
    headers = ["Nº", "INGREDIENTE / MATERIA PRIMA", "CANTIDAD", "UNIDAD / DETALLE"]
    
    # Table header
    for col_idx, h in enumerate(headers):
        cell = tbl_ing.cell(0, col_idx)
        cell.width = col_widths[col_idx]
        set_cell_background(cell, "2B6CB0")
        set_cell_borders(cell, "1E4E8C")
        set_cell_margins(cell, top=70, bottom=70, left=90, right=90)
        p = cell.paragraphs[0]
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER if col_idx != 1 else WD_ALIGN_PARAGRAPH.LEFT
        run = p.add_run(h)
        run.font.name = "Arial"
        run.font.bold = True
        run.font.size = Pt(8.5)
        run.font.color.rgb = RGBColor(255, 255, 255)
        
    for i in range(1, total_rows):
        ing_idx = i - 1
        has_data = ing_idx < len(r['ingredients'])
        bg_col = "F8FAFC" if i % 2 == 0 else "FFFFFF"
        
        # Col 0: Nº
        c0 = tbl_ing.cell(i, 0)
        c0.width = col_widths[0]
        set_cell_background(c0, bg_col)
        set_cell_borders(c0, "CBD5E1")
        set_cell_margins(c0, top=45, bottom=45, left=60, right=60)
        p0 = c0.paragraphs[0]
        p0.alignment = WD_ALIGN_PARAGRAPH.CENTER
        p0.paragraph_format.space_before = Pt(0)
        p0.paragraph_format.space_after = Pt(0)
        r0 = p0.add_run(str(i))
        r0.font.name = "Arial"
        r0.font.size = Pt(8.5)
        r0.font.color.rgb = RGBColor(100, 116, 139)
        
        # Col 1: Ingrediente
        c1 = tbl_ing.cell(i, 1)
        c1.width = col_widths[1]
        set_cell_background(c1, bg_col)
        set_cell_borders(c1, "CBD5E1")
        set_cell_margins(c1, top=45, bottom=45, left=90, right=90)
        p1 = c1.paragraphs[0]
        p1.paragraph_format.space_before = Pt(0)
        p1.paragraph_format.space_after = Pt(0)
        if has_data:
            ing_data = r['ingredients'][ing_idx]
            r1 = p1.add_run(ing_data['ingrediente'])
            r1.font.name = "Arial"
            r1.font.bold = True
            r1.font.size = Pt(8.5)
            r1.font.color.rgb = RGBColor(15, 23, 42)
            
        # Col 2: Cantidad
        c2 = tbl_ing.cell(i, 2)
        c2.width = col_widths[2]
        set_cell_background(c2, bg_col)
        set_cell_borders(c2, "CBD5E1")
        set_cell_margins(c2, top=45, bottom=45, left=90, right=90)
        p2 = c2.paragraphs[0]
        p2.paragraph_format.space_before = Pt(0)
        p2.paragraph_format.space_after = Pt(0)
        p2.alignment = WD_ALIGN_PARAGRAPH.CENTER
        if has_data:
            r2 = p2.add_run(ing_data['cantidad'])
            r2.font.name = "Arial"
            r2.font.bold = True
            r2.font.size = Pt(8.5)
            r2.font.color.rgb = RGBColor(15, 23, 42)
            
        # Col 3: Unidad / Observaciones
        c3 = tbl_ing.cell(i, 3)
        c3.width = col_widths[3]
        set_cell_background(c3, bg_col)
        set_cell_borders(c3, "CBD5E1")
        set_cell_margins(c3, top=45, bottom=45, left=90, right=90)
        p3 = c3.paragraphs[0]
        p3.paragraph_format.space_before = Pt(0)
        p3.paragraph_format.space_after = Pt(0)
        if has_data:
            u_text = ing_data['unidad']
            if ing_data['obs']:
                u_text += f" ({ing_data['obs']})" if u_text else ing_data['obs']
            r3 = p3.add_run(u_text)
            r3.font.name = "Arial"
            r3.font.size = Pt(8)
            r3.font.color.rgb = RGBColor(71, 85, 105)
            
    p_space3 = doc.add_paragraph()
    p_space3.paragraph_format.space_before = Pt(4)
    p_space3.paragraph_format.space_after = Pt(2)
    
    # Process / Notes Table
    tbl_proc = doc.add_table(rows=2, cols=1)
    tbl_proc.alignment = WD_TABLE_ALIGNMENT.CENTER
    tbl_proc.autofit = False
    
    cp_hdr = tbl_proc.cell(0, 0)
    cp_hdr.width = Inches(7.27)
    set_cell_background(cp_hdr, "2D3748")
    set_cell_margins(cp_hdr, top=60, bottom=60, left=90, right=90)
    pp_h = cp_hdr.paragraphs[0]
    pp_h.paragraph_format.space_before = Pt(0)
    pp_h.paragraph_format.space_after = Pt(0)
    rp_h = pp_h.add_run("MÉTODO DE ELABORACIÓN / PROCESO Y PARÁMETROS TÉCNICOS")
    rp_h.font.name = "Arial"
    rp_h.font.bold = True
    rp_h.font.size = Pt(8.5)
    rp_h.font.color.rgb = RGBColor(255, 255, 255)
    
    cp_bdy = tbl_proc.cell(1, 0)
    cp_bdy.width = Inches(7.27)
    set_cell_background(cp_bdy, "FFFFFF")
    set_cell_borders(cp_bdy, "CBD5E1")
    set_cell_margins(cp_bdy, top=80, bottom=80, left=90, right=90)
    pp_b = cp_bdy.paragraphs[0]
    pp_b.paragraph_format.space_before = Pt(0)
    pp_b.paragraph_format.space_after = Pt(0)
    
    proc_lines = []
    if r['proceso']:
        proc_lines.append(r['proceso'].strip())
    if r['notas']:
        proc_lines.extend(r['notas'])
    if not proc_lines:
        proc_lines.append("No se detallan instrucciones de elaboración en el manuscrito original.")
        
    rp_b = pp_b.add_run("\n".join(proc_lines))
    rp_b.font.name = "Arial"
    rp_b.font.size = Pt(8.5)
    rp_b.font.color.rgb = RGBColor(30, 41, 59)
    
    # Add page break except after last recipe
    if r_idx < len(recipes) - 1:
        doc.add_page_break()

doc_path = r'c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\documentacion raul asencio\recetas\Recetario_Completo_Rellenado_Raul_Asencio.docx'
doc.save(doc_path)
print(f"Consolidated Word document saved successfully at: {doc_path}")

