"""Convierte un documento técnico de Synopta (.md con ficha YAML) a .docx con la marca, listo para subir como Google Doc.

Estándar: documentacion/ESTANDAR-DOCUMENTACION.md. Tokens del manual de marca 1.3 (los mismos de propuestas/propuesta.css):
titulares en Newsreader, texto en Manrope, grafito como color base y terracota solo como acento.
Newsreader y Manrope son de Google Fonts, así que Google Docs las respeta al importar.

Uso:  python -X utf8 md_a_doc_synopta.py <entrada.md> <salida.docx>
Entiende: ficha YAML al inicio (clave: valor), # a ####, párrafos, **negrita**, *cursiva*, `código`,
[texto](url), listas (- y 1.), tablas, citas (>) y bloques ``` de código.
"""
import re
import sys

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor

GRAFITO = RGBColor(0x22, 0x26, 0x2A)
GRIS = RGBColor(0x5F, 0x64, 0x6A)
TERRA = RGBColor(0xB5, 0x52, 0x3B)
BLANCO = RGBColor(0xFF, 0xFF, 0xFF)
SERIF, SANS, MONO = "Newsreader", "Manrope", "Roboto Mono"
FICHA_ORDEN = ["codigo", "titulo", "version", "estado", "dueno", "audiencia", "actualizado", "fuente", "drive"]
FICHA_NOMBRE = {"codigo": "Código", "titulo": "Documento", "version": "Versión", "estado": "Estado", "dueno": "Dueño",
                "audiencia": "Audiencia", "actualizado": "Última actualización", "fuente": "Fuente (se edita aquí)",
                "drive": "Copia en Drive"}


def fuente(run, nombre, tam=None, color=None, negrita=None, cursiva=None):
    run.font.name = nombre
    run._element.get_or_add_rPr().get_or_add_rFonts().set(qn("w:eastAsia"), nombre)
    if tam: run.font.size = Pt(tam)
    if color is not None: run.font.color.rgb = color
    if negrita is not None: run.bold = negrita
    if cursiva is not None: run.italic = cursiva


def sombra(celda, hexcolor):
    tcPr = celda._element.get_or_add_tcPr()
    shd = OxmlElement("w:shd"); shd.set(qn("w:val"), "clear"); shd.set(qn("w:color"), "auto"); shd.set(qn("w:fill"), hexcolor)
    tcPr.append(shd)


def bordes_tabla(tabla, color="E2DDD5"):
    tblPr = tabla._element.tblPr
    b = OxmlElement("w:tblBorders")
    for lado in ("top", "left", "bottom", "right", "insideH", "insideV"):
        e = OxmlElement(f"w:{lado}"); e.set(qn("w:val"), "single"); e.set(qn("w:sz"), "4"); e.set(qn("w:color"), color)
        b.append(e)
    tblPr.append(b)


ANCHO_UTIL = 16.6  # cm entre márgenes


def anchos(filas, n):
    """Ancho de cada columna según el largo de su texto (raíz para que una columna larga no aplaste a las otras)."""
    largo = [max(len(re.sub(r"[*`]", "", f[c])) if c < len(f) else 0 for f in filas) for c in range(n)]
    peso = [max(3, l) ** 0.6 for l in largo]
    return [max(1.3, ANCHO_UTIL * w / sum(peso)) for w in peso]


def fila_encabezado(fila):
    trPr = fila._tr.get_or_add_trPr()
    for tag in ("w:tblHeader", "w:cantSplit"):
        e = OxmlElement(tag); e.set(qn("w:val"), "true"); trPr.append(e)


def linea_inferior(par, color="B5523B", grosor="8"):
    pPr = par._element.get_or_add_pPr()
    bdr = OxmlElement("w:pBdr"); e = OxmlElement("w:bottom")
    e.set(qn("w:val"), "single"); e.set(qn("w:sz"), grosor); e.set(qn("w:space"), "4"); e.set(qn("w:color"), color)
    bdr.append(e); pPr.append(bdr)


TOKEN = re.compile(r"(\*\*[^*]+\*\*|\*[^*\s][^*]*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))")


def runs(par, texto, tam=10.5, color=GRAFITO, negrita=False):
    for trozo in TOKEN.split(texto):
        if not trozo:
            continue
        if trozo.startswith("**"):
            fuente(par.add_run(trozo[2:-2]), SANS, tam, color, True)
        elif trozo.startswith("`"):
            fuente(par.add_run(trozo[1:-1]), MONO, tam - 1.5, GRAFITO, negrita)
        elif trozo.startswith("["):
            t, u = re.match(r"\[([^\]]+)\]\(([^)]+)\)", trozo).groups()
            fuente(par.add_run(t), SANS, tam, TERRA, negrita)
            if u != t:
                fuente(par.add_run(f" ({u})"), SANS, tam - 1.5, GRIS, False)
        elif trozo.startswith("*") and trozo.endswith("*") and len(trozo) > 2:
            fuente(par.add_run(trozo[1:-1]), SANS, tam, color, negrita, True)
        else:
            fuente(par.add_run(trozo), SANS, tam, color, negrita)


def espacio(par, antes=0, despues=4, interlineado=1.25):
    pf = par.paragraph_format
    pf.space_before, pf.space_after, pf.line_spacing = Pt(antes), Pt(despues), interlineado


def leer_ficha(lineas):
    ficha = {}
    if lineas and lineas[0].strip() == "---":
        fin = lineas[1:].index("---") + 1
        for l in lineas[1:fin]:
            if ":" in l:
                k, v = l.split(":", 1); ficha[k.strip()] = v.strip().strip('"')
        lineas = lineas[fin + 1:]
    return ficha, lineas


def convertir(src, dst):
    ficha, lineas = leer_ficha(open(src, encoding="utf-8").read().splitlines())
    doc = Document()
    for s in doc.sections:
        s.left_margin = s.right_margin = Cm(2.2); s.top_margin = Cm(2); s.bottom_margin = Cm(2)
        pie = s.footer.paragraphs[0]
        runs(pie, "Synopta Consulting" + (f"  ·  {ficha['codigo']}" if "codigo" in ficha else "")
             + (f"  ·  v{ficha['version']}" if "version" in ficha else ""), tam=8, color=GRIS)
    normal = doc.styles["Normal"]; normal.font.name = SANS; normal.font.size = Pt(10.5); normal.font.color.rgb = GRAFITO

    # cabecera: eyebrow + título + ficha
    if ficha:
        p = doc.add_paragraph(); espacio(p, 0, 2)
        fuente(p.add_run("SYNOPTA  ·  DOCUMENTACIÓN TÉCNICA"), SANS, 8.5, TERRA, True)
    titulo_hecho = False
    i = 0
    while i < len(lineas):
        l = lineas[i].rstrip()
        if not l.strip() or re.fullmatch(r"-{3,}", l.strip()):
            i += 1; continue
        if l.strip().startswith("```"):                     # bloque de código
            i += 1; cod = []
            while i < len(lineas) and not lineas[i].strip().startswith("```"):
                cod.append(lineas[i]); i += 1
            i += 1
            t = doc.add_table(rows=1, cols=1); sombra(t.cell(0, 0), "F6F3EE"); bordes_tabla(t)
            p = t.cell(0, 0).paragraphs[0]; espacio(p, 2, 2, 1.1)
            for k, c in enumerate(cod):
                r = p.add_run(c); fuente(r, MONO, 8.5, GRAFITO)
                if k < len(cod) - 1: r.add_break()
            espacio(doc.add_paragraph(), 0, 2); continue
        m = re.match(r"^(#{1,6})\s+(.*)", l)
        if m:
            nivel, texto = len(m.group(1)), re.sub(r"\*\*", "", m.group(2))
            p = doc.add_paragraph()
            if nivel == 1:
                espacio(p, 0, 8, 1.05); fuente(p.add_run(texto), SERIF, 26, GRAFITO)
                if ficha and not titulo_hecho:
                    titulo_hecho = True; agregar_ficha(doc, ficha)
            elif nivel == 2:
                espacio(p, 16, 6, 1.1); fuente(p.add_run(texto), SERIF, 17, GRAFITO); linea_inferior(p, "E2DDD5", "6")
            elif nivel == 3:
                espacio(p, 10, 3); fuente(p.add_run(texto), SANS, 11.5, GRAFITO, True)
            else:
                espacio(p, 8, 2); fuente(p.add_run(texto.upper()), SANS, 9, TERRA, True)
            p.style = doc.styles[f"Heading {min(nivel, 4)}"]  # mantiene el índice navegable en Google Docs
            p.paragraph_format.keep_with_next = True
            for r in p.runs:
                r.font.color.rgb = TERRA if nivel >= 4 else GRAFITO
            i += 1; continue
        if l.lstrip().startswith("|"):                    # tabla
            filas = []
            while i < len(lineas) and lineas[i].lstrip().startswith("|"):
                celdas = [c.strip() for c in lineas[i].strip().strip("|").split("|")]
                if not all(re.fullmatch(r":?-{2,}:?", c) for c in celdas if c): filas.append(celdas)
                i += 1
            n = max(len(f) for f in filas)
            t = doc.add_table(rows=len(filas), cols=n); t.alignment = WD_TABLE_ALIGNMENT.CENTER; bordes_tabla(t)
            t.autofit = False; w = anchos(filas, n); fila_encabezado(t.rows[0])
            for c in range(n): t.columns[c].width = Cm(w[c])  # Google Docs lee los anchos de la grilla
            for r, f in enumerate(filas):
                for c in range(n):
                    celda = t.cell(r, c); celda.width = Cm(w[c]); p = celda.paragraphs[0]; espacio(p, 1, 1, 1.1)
                    if r < len(filas) - 1: p.paragraph_format.keep_with_next = r == 0
                    if r == 0:
                        sombra(celda, "22262A"); runs(p, f[c] if c < len(f) else "", 9, BLANCO, True)
                    else:
                        runs(p, f[c] if c < len(f) else "", 9)
            espacio(doc.add_paragraph(), 0, 2); continue
        m = re.match(r"^(\s*)([-*·]|\d+\.)\s+(.*)", l)
        if m:
            estilo = "List Number" if m.group(2)[0].isdigit() else "List Bullet"
            if len(m.group(1)) >= 2: estilo += " 2"
            p = doc.add_paragraph(style=estilo); espacio(p, 0, 2); runs(p, m.group(3)); i += 1; continue
        if l.startswith(">"):
            p = doc.add_paragraph(); espacio(p, 4, 6); p.paragraph_format.left_indent = Cm(0.5)
            pPr = p._element.get_or_add_pPr(); bdr = OxmlElement("w:pBdr"); e = OxmlElement("w:left")
            e.set(qn("w:val"), "single"); e.set(qn("w:sz"), "18"); e.set(qn("w:space"), "8"); e.set(qn("w:color"), "B5523B")
            bdr.append(e); pPr.append(bdr)
            runs(p, l.lstrip("> ").strip(), 10.5, GRIS); i += 1; continue
        par = [l.strip()]; i += 1                         # párrafo
        while i < len(lineas) and lineas[i].strip() and not re.match(r"^(#|\||>|```|\s*([-*·]|\d+\.)\s)", lineas[i]):
            par.append(lineas[i].strip()); i += 1
        p = doc.add_paragraph(); espacio(p); runs(p, " ".join(par))
    doc.save(dst)


def agregar_ficha(doc, ficha):
    claves = [k for k in FICHA_ORDEN if k in ficha and k != "titulo"]
    t = doc.add_table(rows=len(claves), cols=2); bordes_tabla(t)
    for r, k in enumerate(claves):
        a, b = t.cell(r, 0), t.cell(r, 1); sombra(a, "F6F3EE")
        a.width, b.width = Cm(4.5), Cm(12)
        t.columns[0].width, t.columns[1].width = Cm(4.5), Cm(12.1)
        pa = a.paragraphs[0]; espacio(pa, 1, 1); runs(pa, FICHA_NOMBRE[k], 8.5, GRIS, True)
        pb = b.paragraphs[0]; espacio(pb, 1, 1); runs(pb, ficha[k], 9)
    p = doc.add_paragraph(); espacio(p, 0, 6)


if __name__ == "__main__":
    convertir(sys.argv[1], sys.argv[2]); print("ok", sys.argv[2])
