"""Export BAB 8 Master Program ke HTML + PDF."""

from html import escape
from pathlib import Path

source = Path("dokumen/Laporan_FS_CMU_GoogleDocs_Rapih.md")
out_html = Path("final/BAB_08_Master_Program_Revisi.html")
text = source.read_text()

# Ambil hanya bagian BAB 8
body_anchor = text.find("RINGKASAN EKSEKUTIF", text.find("RINGKASAN EKSEKUTIF") + 1)
start = text.find("BAB 8 MASTER PROGRAM", body_anchor)
end = text.find("\nBAB 9 PROGRAM FUNGSI", start)
if start == -1 or end == -1:
    raise SystemExit("Cannot find BAB 8 body")
bab8_text = text[start:end].strip()

lines = bab8_text.splitlines()
out = []
i = 0
while i < len(lines):
    stripped = lines[i].strip()
    if not stripped:
        i += 1
        continue
    # Tabel markdown
    if stripped.startswith("|") and "|" in stripped[1:]:
        table = []
        while i < len(lines) and lines[i].strip().startswith("|"):
            row = [c.strip() for c in lines[i].strip().strip("|").split("|")]
            if not all(set(c.replace(":", "").replace("-", "")) == set() for c in row):
                table.append(row)
            i += 1
        if table:
            out.append("<table>")
            for r, row in enumerate(table):
                tag = "th" if r == 0 else "td"
                out.append(
                    "<tr>"
                    + "".join(f"<{tag}>{escape(c)}</{tag}>" for c in row)
                    + "</tr>"
                )
            out.append("</table>")
        continue
    # Heading BAB
    if stripped.startswith("BAB "):
        out.append(f'<h1 class="bab">{escape(stripped)}</h1>')
    # Caption tabel
    elif stripped.startswith("Tabel "):
        out.append(f'<p class="caption">{escape(stripped)}</p>')
    # Sub-heading numerik (8.1.1 dst)
    elif stripped.split()[0].replace(".", "").isdigit() and "." in stripped.split()[0]:
        first = stripped.split()[0]
        if first.count(".") >= 2:
            out.append(f"<h3>{escape(stripped)}</h3>")
        else:
            out.append(f"<h2>{escape(stripped)}</h2>")
    else:
        out.append(f"<p>{escape(stripped)}</p>")
    i += 1

html = (
    """<!doctype html><html><head><meta charset="utf-8">
<title>BAB 8 Master Program - CMU RSUD KH Ahmad Hanafiah</title>
<style>
@page { size: A4; margin: 2.5cm 2cm 2.5cm 2.5cm; }
body { font-family: Arial, sans-serif; font-size: 11pt; line-height: 1.5; color:#111; }
h1 { font-size: 14pt; text-align: center; margin: 20pt 0 14pt; font-weight: bold; }
h1.bab { page-break-before: auto; margin-top: 0; }
h2 { font-size: 12pt; margin: 14pt 0 8pt; font-weight: bold; }
h3 { font-size: 11pt; margin: 12pt 0 6pt; font-weight: bold; }
p { text-align: justify; margin: 0 0 8pt; }
p.caption { text-align:center; font-weight:bold; font-style:italic; margin: 10pt 0 4pt; }
table { border-collapse: collapse; width: 100%; margin: 8pt 0 14pt; font-size: 9pt; }
th, td { border: 1px solid #444; padding: 5pt 6pt; vertical-align: top; }
th { background: #d9e1f2; text-align: center; font-weight: bold; }
tr:nth-child(even) td { background: #f5f7fc; }
</style></head><body>"""
    + "\n".join(out)
    + "</body></html>"
)
out_html.write_text(html)
print(f"HTML written: {out_html}")

# Buat PDF via WeasyPrint jika tersedia
try:
    import weasyprint

    out_pdf = Path("final/BAB_08_Master_Program_Revisi.pdf")
    weasyprint.HTML(filename=str(out_html)).write_pdf(str(out_pdf))
    print(f"PDF written: {out_pdf}")
except ImportError:
    print("WeasyPrint tidak tersedia, gunakan browser/wkhtmltopdf untuk cetak PDF")
