"""Build RTF, DOCX, XLSX, CSV from the cold model output (default run/attempt2_output.md, unedited).
Layout-only transforms (disclosed in the RTF footer, DOCX cover, XLSX Read me and on the page):
 - '(N=xxx)' is split from the column label onto a second header line.
 - Rows with no cells (Baseline, Week 24, Change from Baseline) become section headings; the rows under them are indented.
 - 'Diff. of LS Means (SE)' and '95% CI' rows are indented under their p-value row.
Row order, labels, placeholders and footnotes are exactly as the model wrote them.
Usage: python build_files.py [model_output.md]
"""
import re, os, csv, sys, shutil

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "..", "out", "tlf-shells-from-sap", "files")
os.makedirs(OUT, exist_ok=True)
SRC = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "attempt2_output.md")
DATE = "2026-10-25"
SLUG = "tlf-shells-from-sap"
NOTE = ("Layout only: pipe lines turned into a table, '(N=xxx)' moved under each column name, and section and sub-rows indented. Row order, labels, placeholders "
        "and footnotes are as the model wrote them (raw output: %s_raw_model_output.md)." % SLUG)
FOOT = "Shell only: every value is a placeholder. Generated by Claude on %s from CDISCPILOT01 SAP text; not run on data." % DATE


def parse(path):
    lines = open(path, encoding="utf8").read().splitlines()
    pop = next(l for l in lines if l.startswith("Population:"))[len("Population:"):].strip()
    title = next(l for l in lines if l.startswith("Template 5:"))
    title = title[len("Template 5:"):].strip()
    pipe = [l for l in lines if "|" in l and not re.match(r"\s*\d+\.", l)]
    def split(l):
        if l.startswith("|"):
            return [x.strip() for x in l.strip().strip("|").split("|")]
        return [x.strip() for x in l.split("|")]
    pipe = [split(l) for l in pipe if not re.match(r"\|?[-| ]+\|?$", l.strip())]
    hdr = pipe[0]
    cols = []
    for h in hdr[1:]:
        m = re.match(r"(.*?)\s*(\(N=xxx\))$", h)
        cols.append((m.group(1), m.group(2)) if m else (h, ""))
    rows = [c for c in pipe[1:]]
    foot = [l for l in lines if re.match(r"\[\d\]", l)]
    i = next(k for k, l in enumerate(lines) if re.match(r"(Not settled|Open items)", l))
    oq = [re.sub(r"^\d+\.\s*", "", l) for l in lines[i + 1:] if re.match(r"\d+\.", l)]
    return dict(pop=pop, title=title, cols=cols, rows=rows, foot=foot, oq=oq, first=hdr[0])


def shape(t):
    out = []
    for c in t["rows"]:
        lab, vals = c[0], c[1:]
        if not any(vals):
            out.append(dict(kind="head", cells=[lab] + [""] * len(vals)))
        elif lab in ("N", "Mean (SD)", "Median (Range)") or lab.startswith(("Diff.", "95%")):
            out.append(dict(kind="indent", cells=[lab] + vals))
        else:
            out.append(dict(kind="row", cells=[lab] + vals))
    return out


def esc(s):
    s = s.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
    return "".join(ch if ord(ch) < 128 else "\\u%d?" % ord(ch) for ch in s)


def build_rtf(t, rows, widths):
    n = len(t["cols"]) + 1
    xs, acc = [], 0
    for w in widths:
        acc += w; xs.append(acc)
    o = [r"{\rtf1\ansi\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}"
         r"{\colortbl;\red0\green0\blue0;\red255\green242\blue204;\red242\green242\blue242;\red90\green90\blue90;}"
         r"\paperw12240\paperh15840\margl1440\margr1440\margt1200\margb1200\headery500\footery500\f0\fs17"]
    o.append(r"{\header\pard\plain\f0\fs15\cf4\ql Protocol: CDISCPILOT01 (CDISC SDTM/ADaM Pilot Project)\tab\tab Program: [to be added]   Run date: [to be added]\par}")
    o.append(r"{\footer\pard\plain\f0\fs15\cf4\ql " + esc(FOOT) + r"\tab Page {\field{\*\fldinst PAGE}{\fldrslt 1}} of {\field{\*\fldinst NUMPAGES}{\fldrslt 1}}\par}")
    o.append(r"\pard\plain\f0\qc\fs18\b Table [number to be assigned]\b0\par")
    o.append(r"\pard\plain\f0\qc\fs20\b " + esc(t["title"]) + r"\b0\par")
    o.append(r"\pard\plain\f0\qc\fs17 Population: " + esc(t["pop"]) + r"\par")
    o.append(r"\pard\plain\f0\fs8\par")

    def row(cells, kind, hdr=False, last=False, bold=False):
        s = [r"\trowd\trgaph60\trleft0\trkeep"]
        if hdr: s.append(r"\trhdr")
        for i in range(n):
            b = ""
            if hdr: b += r"\clbrdrt\brdrs\brdrw15\clbrdrb\brdrs\brdrw15\clvertalb"
            if last: b += r"\clbrdrb\brdrs\brdrw15"
            s.append(b + r"\cellx%d" % xs[i])
        s.append("\n")
        for i, c in enumerate(cells):
            al = "ql" if i == 0 else "qc"
            ind = r"\li200" if (i == 0 and kind == "indent") else ""
            txt = esc(c).replace("\n", r"\line ")
            s.append(r"\pard\intbl\plain\f0\fs17\%s%s %s%s%s\cell" % (al, ind, r"\b " if bold else "", txt, r"\b0" if bold else ""))
        s.append(r"\row" + "\n")
        return "".join(s)

    hdr = [t["first"]] + [c[0] + ("\n" + c[1] if c[1] else "") for c in t["cols"]]
    o.append(row(hdr, "row", hdr=True, bold=True))
    for k, r in enumerate(rows):
        o.append(row(r["cells"], r["kind"], last=(k == len(rows) - 1), bold=(r["kind"] == "head")))
    o.append(r"\pard\plain\f0\fs8\par")
    for f in t["foot"]:
        o.append(r"\pard\plain\f0\fs15\ql\li0 " + esc(f) + r"\par")
    o.append(r"\pard\plain\f0\fs8\par")
    o.append(r"\pard\plain\f0\fs15\ql\li0 " + esc(NOTE) + r"\par")
    o.append("}")
    return "\n".join(o)


def build_docx(t, rows, path):
    from docx import Document
    from docx.shared import Pt, Inches, RGBColor
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.enum.table import WD_TABLE_ALIGNMENT
    from docx.enum.style import WD_STYLE_TYPE
    from docx.oxml.ns import qn
    from docx.oxml import OxmlElement
    d = Document()
    sec = d.sections[0]
    sec.page_width, sec.page_height = Inches(8.5), Inches(11)
    sec.left_margin = sec.right_margin = Inches(0.9); sec.top_margin = Inches(0.9); sec.bottom_margin = Inches(0.8)
    st = d.styles
    nm = st["Normal"]; nm.font.name = "Arial"; nm.font.size = Pt(9)
    nm.element.rPr.rFonts.set(qn("w:eastAsia"), "Arial")
    nm.paragraph_format.space_after = Pt(0); nm.paragraph_format.space_before = Pt(0)
    cs = st.add_style("Shell cell", WD_STYLE_TYPE.PARAGRAPH); cs.base_style = nm; cs.font.size = Pt(8.5)
    cs.paragraph_format.space_before = Pt(1.5); cs.paragraph_format.space_after = Pt(1.5)
    fs = st.add_style("Shell footnote", WD_STYLE_TYPE.PARAGRAPH); fs.base_style = nm; fs.font.size = Pt(7.5)
    fs.paragraph_format.space_after = Pt(2)
    GREY = RGBColor(0x5A, 0x5A, 0x5A)
    hp = sec.header.paragraphs[0]; hp.text = "Protocol: CDISCPILOT01 (CDISC SDTM/ADaM Pilot Project)\tProgram: [to be added]   Run date: [to be added]"
    hp.paragraph_format.tab_stops.add_tab_stop(Inches(6.7), alignment=2)
    for r in hp.runs: r.font.size = Pt(7.5); r.font.color.rgb = GREY
    fp = sec.footer.paragraphs[0]
    r = fp.add_run(FOOT + "\tPage "); r.font.size = Pt(7.5); r.font.color.rgb = GREY
    fp.paragraph_format.tab_stops.add_tab_stop(Inches(6.7), alignment=2)

    def field(par, code):
        run = par.add_run(); run.font.size = Pt(7.5)
        for typ, txt in (("begin", None), (None, code), ("end", None)):
            if typ:
                e = OxmlElement("w:fldChar"); e.set(qn("w:fldCharType"), typ)
            else:
                e = OxmlElement("w:instrText"); e.set(qn("xml:space"), "preserve"); e.text = txt
            run._r.append(e)
    field(fp, "PAGE"); r = fp.add_run(" of "); r.font.size = Pt(7.5); field(fp, "NUMPAGES")

    def shade(cell, hexcol):
        tcPr = cell._tc.get_or_add_tcPr(); sh = OxmlElement("w:shd")
        sh.set(qn("w:val"), "clear"); sh.set(qn("w:color"), "auto"); sh.set(qn("w:fill"), hexcol); tcPr.append(sh)

    def borders(cell, **kw):
        tcPr = cell._tc.get_or_add_tcPr(); b = OxmlElement("w:tcBorders")
        for side, sz in kw.items():
            e = OxmlElement("w:" + side); e.set(qn("w:val"), "single"); e.set(qn("w:sz"), str(sz)); e.set(qn("w:color"), "000000"); b.append(e)
        tcPr.append(b)

    c = d.add_paragraph("Table [number to be assigned]"); c.alignment = WD_ALIGN_PARAGRAPH.CENTER; c.runs[0].bold = True
    c = d.add_paragraph(); c.alignment = WD_ALIGN_PARAGRAPH.CENTER
    rr = c.add_run(t["title"]); rr.bold = True; rr.font.size = Pt(10.5)
    c = d.add_paragraph("Population: " + t["pop"]); c.alignment = WD_ALIGN_PARAGRAPH.CENTER; c.paragraph_format.space_after = Pt(8)
    W = [2.6, 1.35, 1.35, 1.35]
    tb = d.add_table(rows=1 + len(rows), cols=4)
    tb.alignment = WD_TABLE_ALIGNMENT.CENTER; tb.autofit = False
    hdr = tb.rows[0]
    trPr = hdr._tr.get_or_add_trPr(); th = OxmlElement("w:tblHeader"); th.set(qn("w:val"), "true"); trPr.append(th)
    hv = [t["first"]] + [c_[0] + ("\n" + c_[1] if c_[1] else "") for c_ in t["cols"]]
    for i, txt in enumerate(hv):
        cell = hdr.cells[i]; cell.width = Inches(W[i]); borders(cell, top=10, bottom=10); shade(cell, "F2F2F2")
        para = cell.paragraphs[0]; para.style = cs
        para.alignment = WD_ALIGN_PARAGRAPH.LEFT if i == 0 else WD_ALIGN_PARAGRAPH.CENTER
        lines = txt.split("\n")
        for j, ln in enumerate(lines):
            run = para.add_run(ln); run.bold = (j == 0)
            if j < len(lines) - 1: run.add_break()
    for k, rw in enumerate(rows):
        row = tb.rows[k + 1]
        trPr = row._tr.get_or_add_trPr(); cs_ = OxmlElement("w:cantSplit"); cs_.set(qn("w:val"), "true"); trPr.append(cs_)
        for i, txt in enumerate(rw["cells"]):
            cell = row.cells[i]; cell.width = Inches(W[i])
            para = cell.paragraphs[0]; para.style = cs
            para.alignment = WD_ALIGN_PARAGRAPH.LEFT if i == 0 else WD_ALIGN_PARAGRAPH.CENTER
            if i == 0 and rw["kind"] == "indent": para.paragraph_format.left_indent = Inches(0.18)
            run = para.add_run(txt)
            if rw["kind"] == "head": run.bold = True
            if k == len(rows) - 1: borders(cell, bottom=10)
    d.add_paragraph().paragraph_format.space_after = Pt(2)
    for f in t["foot"]:
        d.add_paragraph(f, style="Shell footnote")
    d.add_paragraph().paragraph_format.space_after = Pt(2)
    d.add_paragraph(NOTE, style="Shell footnote")
    d.add_page_break()
    p = d.add_paragraph(); rn = p.add_run("About this shell"); rn.bold = True; rn.font.size = Pt(11)
    for line in ["Shell only. Every value is a placeholder; no data were run.",
                 "Generated by Claude on %s from short SAP text plus the SAP's own Template 5 page (CDISCPILOT01 SAP, sections 1.2, 6, 7, 8.1, 10.1.1, Template 5)." % DATE,
                 "Check the table number, column order, populations and footnotes against your own SAP before use.",
                 "Source: SAP in Appendix 9 of the CDISCPILOT01 CSR, CDISC (https://github.com/cdisc-org/sdtm-adam-pilot-project). A public mock submission."]:
        d.add_paragraph(line).paragraph_format.space_after = Pt(3)
    p = d.add_paragraph(); p.paragraph_format.space_before = Pt(8); rn = p.add_run("Open questions from the model (%d)" % len(t["oq"])); rn.bold = True
    d.add_paragraph("Verbatim from the cold run. These are gaps in the pasted text; see the page for how each was checked against the SAP.").paragraph_format.space_after = Pt(4)
    for i, q in enumerate(t["oq"], 1):
        pp = d.add_paragraph("%d.\t%s" % (i, q)); pp.paragraph_format.left_indent = Inches(0.3); pp.paragraph_format.first_line_indent = Inches(-0.3)
        pp.paragraph_format.tab_stops.add_tab_stop(Inches(0.3)); pp.paragraph_format.space_after = Pt(3)
    d.core_properties.title = "Table shell from a SAP (CDISCPILOT01, ADAS-Cog 11)"; d.core_properties.author = "Generated by Claude"
    d.save(path)


def main():
    t = parse(SRC)
    rows = shape(t)
    widths = [3600, 1920, 1920, 1920]
    with open(os.path.join(OUT, SLUG + "_table1_efficacy.rtf"), "w", encoding="ascii", newline="\r\n") as f:
        f.write(build_rtf(t, rows, widths))
    build_docx(t, rows, os.path.join(OUT, SLUG + "_table1_efficacy.docx"))
    colnames = [c[0] + (" " + c[1] if c[1] else "") for c in t["cols"]]
    header = ["row_order", "row_type", "indent", "row_label"] + colnames
    with open(os.path.join(OUT, SLUG + "_shell_structure.csv"), "w", encoding="utf-8-sig", newline="") as f:
        w = csv.writer(f); w.writerow(header)
        for k, r in enumerate(rows, 1):
            w.writerow([k, r["kind"], 1 if r["kind"] == "indent" else 0] + r["cells"])
    from openpyxl import Workbook
    from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
    wb = Workbook(); ws = wb.active; ws.title = "Shell structure"
    ws.append(header)
    for k, r in enumerate(rows, 1):
        ws.append([k, r["kind"], 1 if r["kind"] == "indent" else 0] + r["cells"])
    hf = PatternFill("solid", fgColor="F2F2F2")
    for c in ws[1]:
        c.font = Font(name="Arial", bold=True, size=10); c.fill = hf; c.border = Border(bottom=Side(style="thin"))
        c.alignment = Alignment(wrap_text=True, vertical="bottom")
    for row in ws.iter_rows(min_row=2):
        for c in row: c.font = Font(name="Arial", size=10)
    for col, wd in zip("ABCDEFG", [10, 10, 8, 40, 18, 24, 24]): ws.column_dimensions[col].width = wd
    ws.freeze_panes = "A2"; ws.auto_filter.ref = ws.dimensions
    wq = wb.create_sheet("Open questions"); wq.append(["#", "Open question (verbatim from the model)"])
    for i, q in enumerate(t["oq"], 1): wq.append([i, q])
    for c in wq[1]: c.font = Font(name="Arial", bold=True, size=10); c.fill = hf
    wq.column_dimensions["B"].width = 120
    for row in wq.iter_rows(min_row=2):
        for c in row: c.font = Font(name="Arial", size=10); c.alignment = Alignment(wrap_text=True, vertical="top")
    wr = wb.create_sheet("Read me", 0)
    for l in ["Shell structure for the CDISCPILOT01 ADAS-Cog (11) table (placeholders only; no data were run).",
              "Generated by Claude on %s from SAP text plus the SAP's Template 5 page. Title: %s. Population: %s." % (DATE, t["title"], t["pop"]),
              "One row per shell row; the last three columns hold the cell placeholders. Footnotes: " + " ".join(t["foot"]),
              NOTE]:
        wr.append([l])
    wr.column_dimensions["A"].width = 140
    wb.save(os.path.join(OUT, SLUG + "_shell_structure.xlsx"))
    shutil.copy(SRC, os.path.join(OUT, SLUG + "_raw_model_output.md"))
    shutil.copy(os.path.join(HERE, "input_excerpt3.txt"), os.path.join(OUT, SLUG + "_sap_excerpts.txt"))
    print(len(rows), "rows", len(t["oq"]), "open questions", len(t["foot"]), "footnotes")


if __name__ == "__main__":
    main()
