"""Render archived web curves beside measured Laplace concentration scans."""
from pathlib import Path
import argparse
import csv
import hashlib
import html
import json
import math
import os
import shutil
from scan_evidence import verify_group

ROOT = Path(__file__).resolve().parent
WORKSPACE = ROOT.parents[1]
ARCHIVE = WORKSPACE / "outputs/01a14c4e-7c05-7860-9b2d-861d405f80ce/MC_OXC_Curve_Archive_20261020"
SCAFFOLD = WORKSPACE / ("manuscript_revision_execution_20260928/48_final_validation_redesign_20261005/"
    "parallel_delivery_20261018/02_submission_materials/supplement_scaffold_20261020")
MODULE = WORKSPACE / "rerun_c026_full_20261021/01_laplace_oxc"
os.environ.setdefault("MPLCONFIGDIR", str(ROOT / "tmp/matplotlib"))

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import fitz

FOUR_COLORS = {"00": "#999999", "01": "#104E8B", "10": "#93BFFF", "11": "#000000"}
EIGHT_COLORS = {"000": "#7F7F7F", "001": "#DA8C00", "010": "#0E457C", "011": "#704800",
                "100": "#00D000", "101": "#007A00", "110": "#93BFFF", "111": "#000000"}


def read(path):
    return json.loads(Path(path).read_text(encoding="utf-8-sig"))


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def write(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n", encoding="utf-8")


def case_sources(case, group, record, ranges, designs):
    cid = case["case_id"]
    input_path = MODULE / f"inputs/OXC/{cid.lower()}.json"
    assert sha(input_path) == case["input_sha256"] == designs[cid]["input_source_sha256"], cid
    scientific_input = read(input_path)
    settings = read(ARCHIVE / record["settings_file"])
    source_image = ARCHIVE / record["curve_file"]
    assert sha(source_image) == record["curve_sha256"], cid
    group_root = Path(group["source_directory"])
    if not group_root.is_absolute():
        group_root = ROOT / group_root
    assert group_root.resolve().is_relative_to(WORKSPACE), group_root
    summary = read(group_root / "summary.json")
    if summary["recorded_points"] != summary["planned_points"]:
        raise ValueError(f"Incomplete scan: {cid}")
    with (group_root / "posterior_probabilities.csv").open(encoding="utf-8-sig", newline="") as stream:
        rows = list(csv.DictReader(stream))
    assert len(rows) == summary["planned_points"], cid
    x = np.array([float(row["concentration_mg_L"]) for row in rows])
    assert np.allclose(np.diff(x), 0.1, rtol=0, atol=1e-12), cid
    assert summary["validation_passed"] is True, cid
    controls = settings["requested_controls"]["per_state_priors"]
    mappings = {item["case_manuscript_id"]: item for item in controls
                if item["case_manuscript_id"] is not None}
    state_ids = [state["manuscript_id"] for state in scientific_input["candidate_states"]]
    assert set(mappings) == set(state_ids), f"Candidate set mismatch: {cid}"
    for state in scientific_input["candidate_states"]:
        mapping = mappings[state["manuscript_id"]]
        assert mapping["case_state_event_id"] == state["state_event_id"], cid
        assert sorted(mapping["taken_study_times_h"]) == sorted(
            event["time_h"] for event in state["dose_events"]), cid
    for row in rows:
        if row["status"] == "success":
            vector = np.array([float(row[key]) for key in state_ids])
            assert np.isfinite(vector).all() and (vector >= 0).all() and (vector <= 1).all(), cid
            assert abs(float(vector.sum()) - 1) <= 1e-12, cid
    evidence = verify_group(group_root, group, rows, read(ROOT / "compute/plan.json"), ROOT)
    return dict(case_id=cid, group_id=case["group_id"], group_root=group_root, rows=rows,
                summary=summary, input=scientific_input, settings=settings, mappings=mappings,
                source_image=source_image, record=record, range=ranges[cid], design=designs[cid], evidence=evidence)


def caption(data):
    observation = data["input"]["observations"][0]
    values = [float(row["concentration_mg_L"]) for row in data["rows"]]
    observed = observation["concentration_mg_L"]
    text = ("Concentration-dependent posterior probabilities: (a) virtual-patient MC; "
            "(b) Python (Laplace). MC, Monte Carlo.")
    if min(values) <= observed <= max(values):
        text += " Dashed lines mark the scenario observation."
    else:
        text += f" The observation ({observed:.3f} mg/L) is outside the scanned range."
    if float(data["range"]["web_y_tick_max"]) == 1:
        text += " MC ticks show probability fractions despite the source percent label."
    if len(data["input"]["candidate_states"]) == 3:
        text += " The MC panel retains four labels; the Python panel includes the three specified candidates."
    if data["case_id"] == "C068":
        text += " MC retains a nonzero Scenario11 curve despite requested exclusion; its prior readback was also nonzero."
    failures = data["summary"].get("failed_points", [])
    if failures:
        if len(failures) <= 3:
            points = ", ".join(f"{value:g}" for value in failures)
            text += f" Python output is unavailable at {points} mg/L."
        else:
            text += f" Python output is unavailable at {len(failures)} grid points; curves are not interpolated across them."
    return text


def make_figure(data):
    original = plt.imread(data["source_image"])
    rows = data["rows"]
    x = np.array([float(row["concentration_mg_L"]) for row in rows])
    scale = float(data["range"]["web_y_tick_max"])
    if scale not in (1, 100):
        raise ValueError("Unverified web probability scale")
    fig = plt.figure(figsize=(10, 3.85), dpi=180, facecolor="white")
    panel_x, panel_y, panel_w = 0.015, 0.07, 0.47
    panel_h = panel_w * 10 * (original.shape[0] / original.shape[1]) / 3.85
    left = fig.add_axes([panel_x, panel_y, panel_w, panel_h])
    left.imshow(original, interpolation="none")
    left.set_axis_off()
    ax = fig.add_axes([0.52 + panel_w * 52 / 450,
                       panel_y + panel_h * (1 - 255 / 300),
                       panel_w * 272 / 450, panel_h * 248 / 300])
    observed = data["input"]["observations"][0]["concentration_mg_L"]
    if x.min() <= observed <= x.max():
        ax.axvline(observed, color="#B3B3B3", linestyle=(0, (4, 4)), linewidth=1.5, zorder=1)
    palette = EIGHT_COLORS if len(data["mappings"]) == 8 else FOUR_COLORS
    for state in data["input"]["candidate_states"]:
        key = state["manuscript_id"]
        ui_label = data["mappings"][key]["provisional_ui_label_newest_first"]
        probabilities = []
        for row in rows:
            value = float(row[key]) if row["status"] == "success" else math.nan
            if math.isfinite(value) and not 0 <= value <= 1:
                raise ValueError(f"Invalid probability: {key}")
            probabilities.append(scale * value)
        ax.plot(x, probabilities, color=palette[ui_label], linewidth=1.5,
                label=f"Scenario{ui_label}", zorder=2)
    upper = float(x.max())
    ax.set_xlim(-0.06 * upper, 1.155 * upper)
    ax.set_ylim(-0.05 * scale, 1.05 * scale)
    ticks = list(range(0, int(upper) + 1, 3 if upper <= 20 else 5))
    if upper not in ticks:
        ticks.append(upper)
    ax.set_xticks(ticks)
    ax.set_yticks(np.linspace(0, scale, 6))
    ax.set_xlabel("Concentration (mg/L)", labelpad=2)
    ax.set_ylabel("Posterior probability (%)" if scale == 100 else "Posterior probability", labelpad=3)
    ax.tick_params(length=2.5, width=0.6, pad=2, labelsize=8.5)
    for spine in ax.spines.values():
        spine.set_linewidth(0.6)
        spine.set_color("#444444")
    legend = ax.legend(loc="center left", bbox_to_anchor=(1.04, 0.5), frameon=False,
                       handlelength=1.4, handletextpad=0.6, borderaxespad=0, fontsize=8.5)
    for xpos, letter, method in ((0.022, "a", "Virtual-patient MC"), (0.528, "b", "Python (Laplace)")):
        fig.text(xpos, 0.955, letter, weight="bold", fontsize=11, va="top")
        fig.text(xpos + 0.035, 0.955, method, fontsize=10, va="top")
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()
    width, height = fig.canvas.get_width_height()
    for text in [*fig.texts, *ax.get_xticklabels(), *ax.get_yticklabels(), ax.xaxis.label,
                 ax.yaxis.label, *legend.get_texts()]:
        box = text.get_window_extent(renderer)
        if box.x0 < 0 or box.y0 < 0 or box.x1 > width or box.y1 > height:
            raise ValueError(f"Text outside figure: {data['case_id']}: {text.get_text()}")
    return fig


def export_case(data):
    cid = data["case_id"]
    destination = ROOT / "figures" / cid
    destination.mkdir(parents=True, exist_ok=True)
    for filename in ("posterior_probabilities.csv", "diagnostics_by_point.json", "summary.json", "provenance.json"):
        shutil.copy2(data["group_root"] / filename, destination / filename)
    shutil.copy2(data["source_image"], destination / "mc_original.png")
    shutil.copy2(ARCHIVE / data["record"]["settings_file"], destination / "mc_settings.json")
    fig = make_figure(data)
    for extension in ("png", "svg", "pdf"):
        fig.savefig(destination / f"{cid}.{extension}", dpi=300)
    plt.close(fig)
    text = caption(data)
    (destination / "caption.txt").write_text(text + "\n", encoding="utf-8")
    report = {"model": "OXC", "scenario_id": cid, "group_id": data["group_id"],
              "original_mc_curve_sha256": sha(data["source_image"]),
              "original_image_unchanged": sha(destination / "mc_original.png") == sha(data["source_image"]),
              "mc_numeric_curve_available": False,
              "publication_image_rights_confirmed": False,
              "mc_capture_date_utc": data["record"]["captured_at_utc"],
              "mc_y_tick_max": float(data["range"]["web_y_tick_max"]),
              "python_y_tick_max": float(data["range"]["web_y_tick_max"]),
              "python_source_directory": str(data["group_root"]),
              "python_states": list(data["mappings"]),
              "state_mapping": data["mappings"],
              "scenario_observation": data["input"]["observations"][0],
              "python_failed_points": data["summary"].get("failed_points", []),
              "release_evidence": data["evidence"],
              "mc_prior_readback": {k: v for k, v in data["settings"]["control_readback"].items()
                                    if k.startswith("prop")},
              "text_within_canvas": True, "caption": text,
              "image_format_note": "PDF and SVG contain an original raster MC panel and a vector Python panel."}
    report["files"] = {p.name: sha(p) for p in sorted(destination.iterdir()) if p.is_file() and p.name != "figure_report.json"}
    write(destination / "figure_report.json", report)
    return report


def build_index(all_data, reports):
    rows, sections = [], []
    for data, report in zip(all_data, reports):
        cid = data["case_id"]
        summary = data["summary"]
        concentrations = [float(row["concentration_mg_L"]) for row in data["rows"]]
        row = {"scenario_id": cid, "description": data["design"]["description"],
               "scan_group": data["group_id"], "observation_time_h": data["input"]["observations"][0]["time_h"],
               "observed_concentration_mg_L": data["input"]["observations"][0]["concentration_mg_L"],
               "min_mg_L": min(concentrations), "max_mg_L": max(concentrations),
               "step_mg_L": 0.1, "planned_points": summary["planned_points"],
               "successful_points": summary["successful_points"],
               "failed_points": len(summary.get("failed_points", [])),
               "candidate_count": len(data["mappings"]), "mc_y_tick_max": report["mc_y_tick_max"],
               "figure": f"figures/{cid}/{cid}.png", "mc_source_url": "https://mipd.shinyapps.io/adherence_ASM/"}
        rows.append(row)
        links = " | ".join(f'<a href="figures/{cid}/{name}">{label}</a>' for name, label in (
            (f"{cid}.svg", "SVG"), (f"{cid}.pdf", "PDF"), ("posterior_probabilities.csv", "Probabilities"),
            ("diagnostics_by_point.json", "Diagnostics"), ("mc_settings.json", "MC settings")))
        sections.append(f'<section id="{cid}"><h2>OXC {cid}</h2><p>{html.escape(row["description"])}</p>'
            f'<p>Observation: {row["observed_concentration_mg_L"]:.6g} mg/L at {row["observation_time_h"]:g} h. '
            f'Python scan: {row["min_mg_L"]:g}-{row["max_mg_L"]:g} mg/L, 0.1 mg/L steps; '
            f'{row["successful_points"]}/{row["planned_points"]} valid outputs.</p>'
            f'<img src="{row["figure"]}" alt="Concentration comparison for OXC {cid}" loading="lazy">'
            f'<p class="caption">{html.escape(report["caption"])}</p><p>{links}</p></section>')
    with (ROOT / "scenario_index.csv").open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    nav = " ".join(f'<a href="#{row["scenario_id"]}">{row["scenario_id"]}</a>' for row in rows)
    page = ('<!doctype html><html lang="en"><head><meta charset="utf-8">'
        '<meta name="viewport" content="width=device-width,initial-scale=1">'
        '<title>OXC Concentration-Probability Comparisons</title><style>'
        'body{font:16px/1.5 Arial,Helvetica,sans-serif;margin:0;color:#202020;background:white;letter-spacing:0}'
        'main{max-width:1250px;margin:30px auto;padding:0 24px}h1{font-size:28px}h2{font-size:22px}'
        'nav{display:flex;flex-wrap:wrap;gap:8px 16px}section{border-top:1px solid #ccc;margin-top:32px;padding-top:16px}'
        'img{width:100%;height:auto;display:block}.caption{font-size:14px;color:#444}a{color:#005b8c}'
        '@media(max-width:650px){main{padding:0 12px}h1{font-size:23px}}</style></head><body><main>'
        '<h1>OXC Concentration-Probability Comparisons</h1>'
        '<p>Each figure pairs an external virtual-patient Monte Carlo (MC) curve with a Python-Laplace scan '
        'using the specified scenario inputs. The Python calculation changes only the observed concentration.</p>'
        '<p>MC panels reproduce images captured from the <a href="https://mipd.shinyapps.io/adherence_ASM/">'
        'Adherence ASM application</a> on 19 October 2026. Curve coordinates were unavailable; '
        'comparisons are visual. The deployed MC model and estimator were not independently verified. '
        'C065-C068 retain the recorded prior-control discrepancies. Python grids cover the visible MC '
        'concentration ranges at 0.1 mg/L intervals; 0 mg/L extends below the visible MC traces.</p>'
        '<p><a href="scenario_index.csv">Scenario index</a> | <a href="README.md">Materials and scope</a> | '
        '<a href="OXC_concentration_comparisons.pdf">All figures</a></p><nav>' + nav + '</nav>'
        + "".join(sections) + '</main></body></html>')
    (ROOT / "index.html").write_text(page, encoding="utf-8")
    return rows


def build_collection(all_data, reports):
    document = fitz.open()
    for data, report in zip(all_data, reports):
        page = document.new_page(width=720, height=390)
        title = f"OXC {data['case_id']}. {data['design']['description']}"
        if page.insert_textbox(fitz.Rect(12, 8, 708, 38), title, fontsize=9, fontname="helv") < 0:
            raise ValueError(f"Collection title overflow: {data['case_id']}")
        with fitz.open(ROOT / "figures" / data["case_id"] / f"{data['case_id']}.pdf") as figure:
            page.show_pdf_page(fitz.Rect(0, 43, 720, 320.2), figure, 0)
        if page.insert_textbox(fitz.Rect(12, 331, 708, 382), report["caption"],
                               fontsize=8, fontname="helv") < 0:
            raise ValueError(f"Collection caption overflow: {data['case_id']}")
    document.save(ROOT / "OXC_concentration_comparisons.pdf", deflate=True)
    document.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cases", nargs="+")
    args = parser.parse_args()
    plt.rcParams.update({"font.family": "Arial", "font.size": 9, "pdf.fonttype": 42,
                         "ps.fonttype": 42, "svg.fonttype": "none"})
    plan = read(ROOT / "compute/plan.json")
    groups = {item["group_id"]: item for item in plan["groups"]}
    records = {item["case_id"]: item for item in read(ARCHIVE / "manifest.json")["records"]}
    designs = {d["scenario_id"]: d for d in read(SCAFFOLD / "authoring/data/designs.json") if d["model"] == "OXC"}
    with (ROOT / "audit/visual_scan_ranges.csv").open(encoding="utf-8-sig", newline="") as stream:
        ranges = {row["case_id"]: row for row in csv.DictReader(stream)}
    cases = sorted(plan["cases"], key=lambda case: case["case_id"])
    if args.cases:
        cases = [case for case in cases if case["case_id"] in args.cases]
    all_data = [case_sources(case, groups[case["group_id"]], records[case["case_id"]], ranges, designs) for case in cases]
    reports = [export_case(data) for data in all_data]
    if not args.cases:
        assert len(cases) == len(records) == 44
        build_index(all_data, reports)
        build_collection(all_data, reports)
        write(ROOT / "figure_manifest.json", {"figure_count": len(reports), "figures": reports,
            "source_mc_manifest_sha256": sha(ARCHIVE / "manifest.json"),
            "ranges_sha256": sha(ROOT / "audit/visual_scan_ranges.csv"),
            "plan_sha256": sha(ROOT / "compute/plan.json"), "plot_script_sha256": sha(__file__)})
    print(json.dumps({"figures_written": len(reports), "cases": [case["case_id"] for case in cases]}))


if __name__ == "__main__":
    main()
