import glob, os, re

KB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kb")

SECTIONS = [
    ("Products", ["crear-producto", "tipos-producto", "subir-fotos", "categorias-etiquetas",
                  "imagen-categoria", "variaciones", "producto-agrupado"]),
    ("Orders & Shipping", ["ver-pedidos-1", "ver-pedidos-2", "devoluciones-reembolsos",
                           "costos-envio", "ajustes-zonas-envio", "ajustes-envio-plano",
                           "ajustes-retiro-tienda", "ajustes-envio-gratis"]),
    ("Coupons & Marketing", ["crear-cupon"]),
    ("Payments & Taxes", ["conectar-paypal", "conectar-stripe", "configurar-impuestos",
                          "ajustes-impuestos", "ajustes-ejemplo-impuesto"]),
    ("Website & Content", ["editar-texto", "pagina-nueva-menu", "menu-navegacion", "footer-astra"]),
    ("Reports & Customers", ["cuanto-vendi"]),
    ("Emails", ["correos-automaticos", "configurar-correos"]),
    ("Store Settings", ["ajustes-productos", "ajustes-checkout", "ajustes-cuentas"]),
]

def first_title(path):
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            if line.startswith("# "):
                return line[2:].strip()
    return os.path.basename(path)

def source_url(path):
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            m = re.search(r"https://www\.youtube\.com/watch\?v=[\w-]+", line)
            if m:
                return m.group(0)
    return ""

toc_lines = ["# WooCommerce Knowledge Base", "",
             "> **Purpose:** Step-by-step guidance for managing a WooCommerce store, distilled from official tutorial videos.",
             "> **How to use:** Ask questions about any topic below; each section is self-contained with concrete steps.",
             ""]

body = []

for sec_name, fnames in SECTIONS:
    toc_lines.append(f"## {sec_name}")
    for fn in fnames:
        path = os.path.join(KB, fn + ".md")
        if not os.path.exists(path):
            continue
        title = first_title(path)
        toc_lines.append(f"- [{title}](#{re.sub(r'[^a-z0-9]+', '-', title.lower()).strip('-')})")
        with open(path, "r", encoding="utf-8") as f:
            content = f.read().strip()
        body.append(content)
    toc_lines.append("")

master = "\n".join(toc_lines) + "\n\n---\n\n"
master += "\n\n---\n\n".join(body) + "\n"

with open(os.path.join(KB, "MASTER_KB.md"), "w", encoding="utf-8") as f:
    f.write(master)

print(f"MASTER_KB.md written ({len(master)} chars, {len(body)} sections merged)")