import os
from docx import Document
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

output_dir = r"c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\documentacion raul asencio\recetas"
os.makedirs(output_dir, exist_ok=True)
docx_path = os.path.join(output_dir, "Plantilla_Ficha_Receta_Rellenar.docx")

doc = Document()

# Configuración de márgenes estrechos para formato limpio A4
sections = doc.sections
for section in sections:
    section.top_margin = Inches(0.5)
    section.bottom_margin = Inches(0.5)
    section.left_margin = Inches(0.6)
    section.right_margin = Inches(0.6)

# Función auxiliar para sombreado de celdas
def set_cell_background(cell, color_hex):
    shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color_hex}"/>')
    cell._tc.get_or_add_tcPr().append(shading_elm)

# Función auxiliar para bordes de celda
def set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
    tcPr = cell._tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')
    for m, val in [('top', top), ('bottom', bottom), ('left', left), ('right', right)]:
        node = OxmlElement(f'w:{m}')
        node.set(qn('w:w'), str(val))
        node.set(qn('w:type'), 'dxa')
        tcMar.append(node)
    tcPr.append(tcMar)

# 1. ENCABEZADO CON LOGO Y TÍTULO
header_table = doc.add_table(rows=1, cols=2)
header_table.alignment = WD_TABLE_ALIGNMENT.CENTER
header_table.autofit = False

col_widths = [Inches(4.8), Inches(2.3)]
for row in header_table.rows:
    for idx, width in enumerate(col_widths):
        row.cells[idx].width = width

cell_h_left = header_table.cell(0, 0)
cell_h_right = header_table.cell(0, 1)

p_brand = cell_h_left.paragraphs[0]
p_brand.paragraph_format.space_before = Pt(0)
p_brand.paragraph_format.space_after = Pt(2)
run_brand = p_brand.add_run("RAÚL ASENCIO PASTELERÍAS")
run_brand.bold = True
run_brand.font.size = Pt(16)
run_brand.font.color.rgb = RGBColor(0x3E, 0x27, 0x23) # Marrón chocolate obrador

p_title = cell_h_left.add_paragraph()
p_title.paragraph_format.space_before = Pt(0)
p_title.paragraph_format.space_after = Pt(0)
run_title = p_title.add_run("FICHA TÉCNICA DE RECETA / FORMULACIÓN")
run_title.bold = True
run_title.font.size = Pt(12)
run_title.font.color.rgb = RGBColor(0x5D, 0x40, 0x37)

logo_path = r"c:\fuentes\proyectos delphi\RAUL_ASENCIO\GESTION\logo_raul.png"
p_logo = cell_h_right.paragraphs[0]
p_logo.alignment = WD_ALIGN_PARAGRAPH.RIGHT
if os.path.exists(logo_path):
    p_logo.add_run().add_picture(logo_path, width=Inches(1.8))
else:
    r_alt = p_logo.add_run("OBRADOR ARTESANAL")
    r_alt.bold = True
    r_alt.font.size = Pt(11)

p_sep = doc.add_paragraph()
p_sep.paragraph_format.space_before = Pt(4)
p_sep.paragraph_format.space_after = Pt(4)
run_line = p_sep.add_run("—" * 68)
run_line.font.color.rgb = RGBColor(0x8D, 0x6E, 0x63)

# 2. CUADRO DE CABECERA: NOMBRE DE RECETA + CHECK PREELABORADO + METADATOS
meta_table = doc.add_table(rows=2, cols=2)
meta_table.alignment = WD_TABLE_ALIGNMENT.CENTER
meta_table.autofit = False

meta_widths = [Inches(4.6), Inches(2.5)]
for row in meta_table.rows:
    for idx, width in enumerate(meta_widths):
        row.cells[idx].width = width

# Celda Receta
c_receta = meta_table.cell(0, 0)
set_cell_background(c_receta, "F5F0EB")
set_cell_margins(c_receta, top=120, bottom=120, left=150, right=150)
p_rec = c_receta.paragraphs[0]
p_rec.paragraph_format.space_after = Pt(0)
r_lbl = p_rec.add_run("RECETA: ")
r_lbl.bold = True
r_lbl.font.size = Pt(11)
r_lbl.font.color.rgb = RGBColor(0x3E, 0x27, 0x23)
r_dots = p_rec.add_run("_______________________________________")
r_dots.bold = True
r_dots.font.color.rgb = RGBColor(0x42, 0x42, 0x42)

# Celda Preelaborado Checkbox
c_preelab = meta_table.cell(0, 1)
set_cell_background(c_preelab, "EFEBE9")
set_cell_margins(c_preelab, top=120, bottom=120, left=150, right=150)
p_pre = c_preelab.paragraphs[0]
p_pre.alignment = WD_ALIGN_PARAGRAPH.CENTER
p_pre.paragraph_format.space_after = Pt(0)
r_pre_lbl = p_pre.add_run("¿ES PREELABORADO?\n")
r_pre_lbl.bold = True
r_pre_lbl.font.size = Pt(10)
r_pre_lbl.font.color.rgb = RGBColor(0x3E, 0x27, 0x23)

r_check = p_pre.add_run("⬜ SÍ        ⬜ NO")
r_check.bold = True
r_check.font.size = Pt(11)
r_check.font.color.rgb = RGBColor(0x21, 0x21, 0x21)

# Fila 2: Fecha y Responsable / Código
c_fec = meta_table.cell(1, 0)
set_cell_background(c_fec, "FAFAFA")
set_cell_margins(c_fec, top=80, bottom=80, left=150, right=150)
p_fec = c_fec.paragraphs[0]
p_fec.paragraph_format.space_after = Pt(0)
r_fec = p_fec.add_run("FECHA: ")
r_fec.bold = True
r_fec.font.size = Pt(9.5)
p_fec.add_run("____ / ____ / 202___     ")
r_resp = p_fec.add_run("RESPONSABLE: ")
r_resp.bold = True
r_resp.font.size = Pt(9.5)
p_fec.add_run("_____________________")

c_lote = meta_table.cell(1, 1)
set_cell_background(c_lote, "FAFAFA")
set_cell_margins(c_lote, top=80, bottom=80, left=150, right=150)
p_lote = c_lote.paragraphs[0]
p_lote.paragraph_format.space_after = Pt(0)
r_lote = p_lote.add_run("CÓDIGO / VERSIÓN: ")
r_lote.bold = True
r_lote.font.size = Pt(9.5)
p_lote.add_run("_____________")

# 3. TABLA DE INGREDIENTES Y CANTIDADES
p_gap = doc.add_paragraph()
p_gap.paragraph_format.space_before = Pt(6)
p_gap.paragraph_format.space_after = Pt(4)

NUM_ROWS = 22
table = doc.add_table(rows=NUM_ROWS + 2, cols=4)
table.alignment = WD_TABLE_ALIGNMENT.CENTER
table.autofit = False

# Anchos: Nº (0.5 in), Ingrediente (3.8 in), Cantidad (1.8 in), Unidad (1.0 in)
t_widths = [Inches(0.45), Inches(3.85), Inches(1.8), Inches(1.0)]
for row in table.rows:
    for idx, width in enumerate(t_widths):
        row.cells[idx].width = width

# Encabezado tabla
headers_text = ["Nº", "INGREDIENTE / MATERIA PRIMA", "CANTIDAD (g o ml)", "UNIDAD"]
for col_idx, h_text in enumerate(headers_text):
    cell = table.cell(0, col_idx)
    set_cell_background(cell, "3E2723") # Fondo marrón chocolate oscuro
    set_cell_margins(cell, top=100, bottom=100, left=100, right=100)
    cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    p = cell.paragraphs[0]
    p.paragraph_format.space_after = Pt(0)
    if col_idx in [0, 2, 3]:
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    else:
        p.alignment = WD_ALIGN_PARAGRAPH.LEFT
    r = p.add_run(h_text)
    r.bold = True
    r.font.size = Pt(9.5)
    r.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)

# Filas de ingredientes
for r_idx in range(1, NUM_ROWS + 1):
    bg_color = "F9F8F6" if r_idx % 2 == 1 else "FFFFFF"
    
    # Celda número
    c_n = table.cell(r_idx, 0)
    set_cell_background(c_n, bg_color)
    set_cell_margins(c_n, top=70, bottom=70, left=80, right=80)
    p_n = c_n.paragraphs[0]
    p_n.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_n.paragraph_format.space_after = Pt(0)
    r_n = p_n.add_run(str(r_idx))
    r_n.font.size = Pt(9.5)
    r_n.font.color.rgb = RGBColor(0x75, 0x75, 0x75)
    
    # Celda ingrediente
    c_i = table.cell(r_idx, 1)
    set_cell_background(c_i, bg_color)
    set_cell_margins(c_i, top=70, bottom=70, left=100, right=100)
    c_i.paragraphs[0].paragraph_format.space_after = Pt(0)
    
    # Celda cantidad
    c_q = table.cell(r_idx, 2)
    set_cell_background(c_q, bg_color)
    set_cell_margins(c_q, top=70, bottom=70, left=100, right=100)
    c_q.paragraphs[0].paragraph_format.space_after = Pt(0)
    
    # Celda unidad
    c_u = table.cell(r_idx, 3)
    set_cell_background(c_u, bg_color)
    set_cell_margins(c_u, top=70, bottom=70, left=80, right=80)
    p_u = c_u.paragraphs[0]
    p_u.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p_u.paragraph_format.space_after = Pt(0)
    r_u = p_u.add_run("[ g / ml ]")
    r_u.font.size = Pt(8.5)
    r_u.font.color.rgb = RGBColor(0xBD, 0xBD, 0xBD)

# Fila total
total_row_idx = NUM_ROWS + 1
c_tot_lbl = table.cell(total_row_idx, 0)
# Combinar 0 y 1
c_tot_lbl.merge(table.cell(total_row_idx, 1))
set_cell_background(c_tot_lbl, "EFEBE9")
set_cell_margins(c_tot_lbl, top=90, bottom=90, left=120, right=120)
p_tl = c_tot_lbl.paragraphs[0]
p_tl.alignment = WD_ALIGN_PARAGRAPH.RIGHT
p_tl.paragraph_format.space_after = Pt(0)
r_tl = p_tl.add_run("PESO / VOLUMEN TOTAL FORMULACIÓN:")
r_tl.bold = True
r_tl.font.size = Pt(9.5)
r_tl.font.color.rgb = RGBColor(0x3E, 0x27, 0x23)

c_tot_val = table.cell(total_row_idx, 2)
set_cell_background(c_tot_val, "EFEBE9")
set_cell_margins(c_tot_val, top=90, bottom=90, left=100, right=100)
c_tot_val.paragraphs[0].paragraph_format.space_after = Pt(0)

c_tot_u = table.cell(total_row_idx, 3)
set_cell_background(c_tot_u, "EFEBE9")
set_cell_margins(c_tot_u, top=90, bottom=90, left=80, right=80)
p_tu = c_tot_u.paragraphs[0]
p_tu.alignment = WD_ALIGN_PARAGRAPH.CENTER
p_tu.paragraph_format.space_after = Pt(0)
r_tu = p_tu.add_run("g / ml")
r_tu.bold = True
r_tu.font.size = Pt(9)
r_tu.font.color.rgb = RGBColor(0x3E, 0x27, 0x23)

# Aplicar bordes suaves a la tabla mediante XML de tblBorders
tblPr = table._tbl.tblPr
borders_elm = parse_xml(
    f'<w:tblBorders {nsdecls("w")}>'
    f'  <w:top w:val="single" w:sz="6" w:space="0" w:color="5D4037"/>'
    f'  <w:bottom w:val="single" w:sz="6" w:space="0" w:color="5D4037"/>'
    f'  <w:left w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'  <w:right w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'  <w:insideH w:val="single" w:sz="4" w:space="0" w:color="E0E0E0"/>'
    f'  <w:insideV w:val="single" w:sz="4" w:space="0" w:color="E0E0E0"/>'
    f'</w:tblBorders>'
)
tblPr.append(borders_elm)

# 4. PIE DE PÁGINA: NOTAS / PASOS DE ELABORACIÓN
p_obs = doc.add_paragraph()
p_obs.paragraph_format.space_before = Pt(6)
p_obs.paragraph_format.space_after = Pt(2)
r_obs_title = p_obs.add_run("OBSERVACIONES / MÉTODO DE ELABORACIÓN O PROCESO:")
r_obs_title.bold = True
r_obs_title.font.size = Pt(9)
r_obs_title.font.color.rgb = RGBColor(0x5D, 0x40, 0x37)

box_obs = doc.add_table(rows=1, cols=1)
box_obs.alignment = WD_TABLE_ALIGNMENT.CENTER
box_obs.autofit = False
box_obs.rows[0].cells[0].width = Inches(7.1)
c_box = box_obs.cell(0, 0)
set_cell_background(c_box, "FAFAFA")
set_cell_margins(c_box, top=120, bottom=120, left=150, right=150)
p_box = c_box.paragraphs[0]
p_box.paragraph_format.space_after = Pt(28) # Altura para escribir notas

tblPr_obs = box_obs._tbl.tblPr
borders_obs = parse_xml(
    f'<w:tblBorders {nsdecls("w")}>'
    f'  <w:top w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'  <w:bottom w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'  <w:left w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'  <w:right w:val="single" w:sz="4" w:space="0" w:color="CCCCCC"/>'
    f'</w:tblBorders>'
)
tblPr_obs.append(borders_obs)

doc.save(docx_path)
print(f"Word (.docx) guardado exitosamente en: {docx_path}")

