#!/usr/bin/env python3
"""Build the Kangbite-branded Word proposal from the reviewed Markdown source."""

from __future__ import annotations

import argparse
import re
from pathlib import Path

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK, WD_LINE_SPACING
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor


ORANGE = "F57C00"
NAVY = "17324D"
BLUE = "2563A7"
PALE_ORANGE = "FFF3E8"
PALE_BLUE = "EEF5FB"
GRAY = "667085"


def set_cell_shading(cell, fill: str) -> None:
    tc_pr = cell._tc.get_or_add_tcPr()
    shd = tc_pr.find(qn("w:shd"))
    if shd is None:
        shd = OxmlElement("w:shd")
        tc_pr.append(shd)
    shd.set(qn("w:fill"), fill)


def set_cell_margins(cell, top=90, start=100, bottom=90, end=100) -> None:
    tc = cell._tc
    tc_pr = tc.get_or_add_tcPr()
    tc_mar = tc_pr.first_child_found_in("w:tcMar")
    if tc_mar is None:
        tc_mar = OxmlElement("w:tcMar")
        tc_pr.append(tc_mar)
    for m, value in (("top", top), ("start", start), ("bottom", bottom), ("end", end)):
        node = tc_mar.find(qn(f"w:{m}"))
        if node is None:
            node = OxmlElement(f"w:{m}")
            tc_mar.append(node)
        node.set(qn("w:w"), str(value))
        node.set(qn("w:type"), "dxa")


def set_repeat_table_header(row) -> None:
    tr_pr = row._tr.get_or_add_trPr()
    tbl_header = OxmlElement("w:tblHeader")
    tbl_header.set(qn("w:val"), "true")
    tr_pr.append(tbl_header)


def font_run(run, size=10.5, bold=False, color=NAVY, name="Arial Unicode MS") -> None:
    run.font.name = name
    run._element.rPr.rFonts.set(qn("w:eastAsia"), name)
    run.font.size = Pt(size)
    run.font.bold = bold
    run.font.color.rgb = RGBColor.from_string(color)


def add_inline(paragraph, text: str, size=10.5, color=NAVY, bold_all=False) -> None:
    """Render minimal Markdown emphasis without importing a full converter."""
    parts = re.split(r"(\*\*.+?\*\*|`.+?`)", text)
    for part in parts:
        if not part:
            continue
        is_bold = part.startswith("**") and part.endswith("**")
        is_code = part.startswith("`") and part.endswith("`")
        clean = part[2:-2] if is_bold else part[1:-1] if is_code else part
        run = paragraph.add_run(clean)
        font_run(run, size=size, bold=bold_all or is_bold, color=ORANGE if is_bold else color,
                 name="Menlo" if is_code else "Arial Unicode MS")


def set_body_paragraph(p, after=4, before=0, line=1.2) -> None:
    fmt = p.paragraph_format
    fmt.space_before = Pt(before)
    fmt.space_after = Pt(after)
    fmt.line_spacing = line
    fmt.keep_together = False
    fmt.widow_control = True


def add_heading(doc, text: str, level: int) -> None:
    p = doc.add_paragraph()
    if level == 2:
        p.paragraph_format.page_break_before = True
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(10)
        r = p.add_run(text)
        font_run(r, size=18, bold=True, color=NAVY)
        p_bdr = OxmlElement("w:pBdr")
        bottom = OxmlElement("w:bottom")
        bottom.set(qn("w:val"), "single")
        bottom.set(qn("w:sz"), "14")
        bottom.set(qn("w:space"), "5")
        bottom.set(qn("w:color"), ORANGE)
        p_bdr.append(bottom)
        p._p.get_or_add_pPr().append(p_bdr)
    elif level == 3:
        p.paragraph_format.space_before = Pt(9)
        p.paragraph_format.space_after = Pt(4)
        r = p.add_run(text)
        font_run(r, size=13.5, bold=True, color=BLUE)
    else:
        p.paragraph_format.space_before = Pt(5)
        p.paragraph_format.space_after = Pt(3)
        r = p.add_run(text)
        font_run(r, size=11.5, bold=True, color=NAVY)


def add_quote(doc, text: str) -> None:
    table = doc.add_table(rows=1, cols=1)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.autofit = False
    cell = table.cell(0, 0)
    cell.width = Cm(15.8)
    set_cell_shading(cell, PALE_ORANGE)
    set_cell_margins(cell, top=150, start=220, bottom=150, end=220)
    p = cell.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    add_inline(p, text.strip(), size=12, color=NAVY, bold_all=True)
    set_body_paragraph(p, after=0, line=1.15)
    doc.add_paragraph().paragraph_format.space_after = Pt(0)


def add_markdown_table(doc, rows: list[list[str]]) -> None:
    if not rows:
        return
    cols = max(len(r) for r in rows)
    table = doc.add_table(rows=len(rows), cols=cols)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.autofit = True
    table.style = "Table Grid"
    for i, row in enumerate(rows):
        for j in range(cols):
            cell = table.cell(i, j)
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
            set_cell_margins(cell)
            if i == 0:
                set_cell_shading(cell, NAVY)
            elif i % 2 == 0:
                set_cell_shading(cell, "F7F9FC")
            p = cell.paragraphs[0]
            add_inline(p, row[j] if j < len(row) else "", size=8.8,
                       color="FFFFFF" if i == 0 else NAVY, bold_all=(i == 0))
            set_body_paragraph(p, after=0, line=1.05)
    set_repeat_table_header(table.rows[0])
    doc.add_paragraph().paragraph_format.space_after = Pt(0)


def parse_markdown(doc, path: Path) -> None:
    lines = path.read_text(encoding="utf-8").splitlines()
    table_rows: list[list[str]] = []
    skip_first_title = True

    def flush_table() -> None:
        nonlocal table_rows
        if table_rows:
            usable = [r for r in table_rows if not all(re.fullmatch(r"\s*:?-{3,}:?\s*", c) for c in r)]
            add_markdown_table(doc, usable)
            table_rows = []

    for raw in lines:
        line = raw.rstrip()
        if line.startswith("|") and line.endswith("|"):
            table_rows.append([c.strip() for c in line.strip("|").split("|")])
            continue
        flush_table()
        if not line:
            continue
        if line.startswith("# "):
            if skip_first_title:
                skip_first_title = False
                continue
            add_heading(doc, line[2:].strip(), 2)
        elif line.startswith("## "):
            add_heading(doc, line[3:].strip(), 2)
        elif line.startswith("### "):
            add_heading(doc, line[4:].strip(), 3)
        elif line.startswith("#### "):
            add_heading(doc, line[5:].strip(), 4)
        elif line.startswith("> "):
            add_quote(doc, line[2:])
        elif re.match(r"^\d+\.\s+", line):
            match = re.match(r"^(\d+)\.\s+(.+)$", line)
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Cm(0.45)
            p.paragraph_format.first_line_indent = Cm(-0.45)
            add_inline(p, f"{match.group(1)}. {match.group(2)}", size=10.2)
            set_body_paragraph(p, after=3, line=1.18)
        elif line.startswith("- "):
            p = doc.add_paragraph()
            p.paragraph_format.left_indent = Cm(0.45)
            p.paragraph_format.first_line_indent = Cm(-0.45)
            add_inline(p, "• " + line[2:], size=10.2)
            set_body_paragraph(p, after=3, line=1.18)
        else:
            p = doc.add_paragraph()
            add_inline(p, line, size=10.3)
            set_body_paragraph(p)
    flush_table()


def configure_styles(doc: Document) -> None:
    styles = doc.styles
    for style_name in ("Normal",):
        style = styles[style_name]
        style.font.name = "Arial Unicode MS"
        style._element.rPr.rFonts.set(qn("w:eastAsia"), "Arial Unicode MS")
        style.font.size = Pt(10.5)
        style.font.color.rgb = RGBColor.from_string(NAVY)
    styles["Normal"].paragraph_format.space_after = Pt(4)
    styles["Normal"].paragraph_format.line_spacing = 1.2


def add_cover(doc: Document) -> None:
    for _ in range(3):
        doc.add_paragraph()
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = p.add_run("康比特智慧食堂")
    font_run(r, size=17, bold=True, color=ORANGE)
    p.paragraph_format.space_after = Pt(12)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = p.add_run("抖音价值营销完整方案")
    font_run(r, size=28, bold=True, color=NAVY)
    p.paragraph_format.space_after = Pt(12)

    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = p.add_run("聚焦千人级复杂组织职工食堂")
    font_run(r, size=16, bold=True, color=BLUE)
    p.paragraph_format.space_after = Pt(18)

    add_quote(doc, "一个场景、一个品类、一个会诊入口，打穿再扩张。")

    table = doc.add_table(rows=2, cols=2)
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    items = [
        ("唯一场景", "千人级复杂组织职工食堂"),
        ("品类主张", "AI 营养健康职工食堂运营 OS"),
        ("抖音任务", "高质量商机转化"),
        ("价值组合", "功能 70%｜情绪 20%｜IP 10%"),
    ]
    for i, (label, value) in enumerate(items):
        cell = table.cell(i // 2, i % 2)
        set_cell_shading(cell, PALE_BLUE if i % 2 == 0 else PALE_ORANGE)
        set_cell_margins(cell, top=180, start=180, bottom=180, end=180)
        p = cell.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        rr = p.add_run(label + "\n")
        font_run(rr, size=9.5, bold=True, color=GRAY)
        rr = p.add_run(value)
        font_run(rr, size=11, bold=True, color=NAVY)
    doc.add_paragraph()
    p = doc.add_paragraph()
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    for text, size, color in [
        ("决策版 · REVIEW-READY\n", 10, GRAY),
        ("康比特数字体育科技｜2026 年 8 月", 10.5, NAVY),
    ]:
        rr = p.add_run(text)
        font_run(rr, size=size, bold=(color == NAVY), color=color)
    p.add_run().add_break(WD_BREAK.PAGE)


def add_footer(section) -> None:
    footer = section.footer
    p = footer.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.clear()
    r = p.add_run("康比特智慧食堂抖音价值营销方案｜内部讨论版")
    font_run(r, size=8, color=GRAY)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--template", required=True)
    parser.add_argument("--source", required=True)
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    doc = Document(args.template)
    configure_styles(doc)
    section = doc.sections[0]
    section.top_margin = Cm(2.54)
    section.bottom_margin = Cm(2.54)
    section.left_margin = Cm(3.175)
    section.right_margin = Cm(3.175)
    add_footer(section)
    add_cover(doc)
    parse_markdown(doc, Path(args.source))

    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)
    doc.core_properties.title = "康比特智慧食堂抖音价值营销完整方案"
    doc.core_properties.subject = "千人级复杂组织职工食堂｜AI 营养健康职工食堂运营 OS"
    doc.core_properties.author = "康比特数字体育科技"
    doc.save(out)
    print(out)


if __name__ == "__main__":
    main()
