"""Regenerate approved panel designs using selected finite five-run posteriors.

Only this delivery's figures/ tree is writable. No computational model is run.
The legacy modules are parsed, not imported: only drawing functions/constants
are executed, so none of their historical data loaders or output paths run.
"""
from __future__ import annotations

import argparse
import ast
import copy
import csv
import hashlib
import importlib.util
import json
import math
import os
from pathlib import Path
import statistics
import sys

ROOT = Path(__file__).resolve().parents[1]
WORKSPACE = Path('D:/AI-ready PMX benchmark engine').resolve()
BASE = WORKSPACE / 'manuscript_revision_execution_20260928/48_final_validation_redesign_20261005'
assert ROOT == BASE / 'delivery_updates/fullresults_figures_20261023/figures'
assert Path.cwd().resolve().is_relative_to(WORKSPACE)
OLD = BASE / 'results_figures_20261017'
SUPPLEMENT = BASE / 'parallel_delivery_20261018/02_submission_materials/supplement_scaffold_20261020'
os.environ['MPLCONFIGDIR'] = str(ROOT / 'qa/mplconfig')
sys.dont_write_bytecode = True
if importlib.util.find_spec('matplotlib') is None:
    sys.path.append('C:/Users/ZJM/AppData/Local/Programs/Python/Python312/Lib/site-packages')
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerTuple
from matplotlib.ticker import NullLocator
import numpy as np

HASHES = {}
LABELS = ['omega_00', 'omega_01', 'omega_10', 'omega_11']
METHODS = ['python_laplace', 'nonmem_laplace', 'r_aghq']
PAIRS = {'package_native': METHODS[:2], 'package_ghq': [METHODS[0], METHODS[2]],
         'native_ghq': METHODS[1:]}


def output(path):
    path = (ROOT / path).resolve()
    assert path.is_relative_to(ROOT), path
    path.parent.mkdir(parents=True, exist_ok=True)
    return path


def read(path):
    path = Path(path).resolve()
    assert path.is_relative_to(WORKSPACE), path
    raw = path.read_bytes()
    HASHES[str(path)] = hashlib.sha256(raw).hexdigest()
    return json.loads(raw.decode('utf-8-sig'))


def write(path, data):
    output(path).write_text(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) + '\n', encoding='utf-8')


def table(path, rows):
    if not rows:
        return
    keys = list(dict.fromkeys(k for row in rows for k in row))
    with output(path).open('w', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=keys)
        writer.writeheader()
        writer.writerows({k: json.dumps(v, ensure_ascii=False) if isinstance(v, (dict, list)) else v
                         for k, v in row.items()} for row in rows)


def source_data():
    designs = read(SUPPLEMENT / 'authoring/data/designs.json')
    results = read(SUPPLEMENT / 'authoring/data/results.json')
    write('data/supplement_diagnostics_unmodified.json', read(SUPPLEMENT / 'authoring/data/diagnostics.json'))
    manifests = {r['manifest_id']: r for r in read(SUPPLEMENT / 'authoring/data/run_manifests.json')}
    registry = {(r['model'], r['scenario_id']): r for r in designs}
    means, raw_records, exclusions = {}, [], []
    for r in results:
        if r['method'] not in METHODS:
            continue
        key = r['model'], r['scenario_id'], r['method']
        if r['n_runs'] != 5 or not r['values']:
            exclusions.append(dict(model=key[0], case_id=key[1], method=key[2], reason='No complete selected five-run posterior', source_result=r,
                                   source_evidence=read(SUPPLEMENT / r['source_path']) if r.get('source_path') else None))
            continue
        d = registry[key[:2]]
        ids = [s['state_event_id'] for s in d['states']]
        assert len(set(ids)) == len(ids)
        assert set(ids) == set(r['values'])
        assert d['design_fingerprint'] == r['design_fingerprint']
        assert len(r['run_ids']) == len(set(r['run_ids'])) == 5
        manifest = manifests[r['run_manifest_id']]
        assert set(manifest['run_ids']) == set(r['run_ids'])
        evidence = read(SUPPLEMENT / r['source_path'])
        assert HASHES[str((SUPPLEMENT / r['source_path']).resolve())] == r['source_sha256']
        derived = evidence.get('derived', evidence)
        case = evidence.get('case', evidence)
        assert case['design_fingerprint'] == d['design_fingerprint']
        assert all(case['mapping_checks'].values())
        runs = evidence.get('run_evidence', case.get('runs', []))
        selected = [run for run in runs if run['run_id'] in r['run_ids']]
        assert len(selected) == 5, key
        assert all(run.get('phase', 'formal') == 'formal' for run in selected)
        raw = derived['raw_vectors']
        assert len(raw) == derived['n_runs'] == 5
        assert all(set(v) == set(ids) for v in raw)
        vectors = [[float(v[i]) for i in ids] for v in raw]
        assert all(math.isfinite(x) and 0 <= x <= 1 for v in vectors for x in v), key
        assert all(abs(math.fsum(v) - 1) <= 1e-6 for v in vectors), key
        normalized = [[x / math.fsum(v) for x in v] for v in vectors]
        mean = [statistics.mean(v[i] for v in normalized) for i in range(len(ids))]
        assert abs(math.fsum(mean) - 1) < 1e-14
        assert max(abs(mean[i] - r['values'][s]) for i, s in enumerate(ids)) < 1e-12, key
        means[key] = dict(model=key[0], case_id=key[1], method=key[2], state_ids=ids,
                          labels=[s['state_id'] for s in d['states']], posterior=mean,
                          run_ids=r['run_ids'], n_runs=5, source_path=r['source_path'],
                          source_sha256=r['source_sha256'], design_fingerprint=d['design_fingerprint'])
        raw_records.append(dict(model=key[0], case_id=key[1], method=key[2],
            raw_vectors=raw, normalized_vectors=[dict(zip(ids, v)) for v in normalized],
            selected_run_ids=r['run_ids'], original_result=r,
            original_case_diagnostics={k:v for k,v in case.items() if k not in ['source_inputs', 'descriptive_summary', 'runs', 'run_evidence', 'raw_vectors', 'normalized_vectors', 'mean_vector']},
            original_runs=runs, selected_run_count=len(selected),
            diagnostic_flags_used_for_exclusion=False))
    return registry, means, raw_records, exclusions


def legacy_renderer(relative, functions, constants, figure1=False):
    path = OLD / relative
    raw = path.read_bytes()
    HASHES[str(path)] = hashlib.sha256(raw).hexdigest()
    output('scripts/style_source/' + path.name).write_bytes(raw)
    tree = ast.parse(raw.decode('utf-8-sig'))
    nodes = [node for node in tree.body if
             isinstance(node, ast.FunctionDef) and node.name in functions or
             isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id in constants for t in node.targets)]
    if figure1:
        class UpdateText(ast.NodeTransformer):
            def visit_Constant(self, node):
                changes = {
                    'GHQ maximum: CL IIV 11.1% to 33.3%': 'R aghq maximum: CL IIV 33.3%',
                    'GHQ maximum: observation 24 to 16 h': 'R aghq maximum: observation at 16 h',
                }
                if isinstance(node.value, str) and node.value in changes:
                    node.value = changes[node.value]
                return node
        nodes = [UpdateText().visit(node) for node in nodes]
    ns = dict(matplotlib=matplotlib, plt=plt, np=np, math=math, Line2D=Line2D,
              Patch=Patch, HandlerTuple=HandlerTuple, NullLocator=NullLocator)
    exec(compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])), str(path), 'exec'), ns)
    if figure1:
        ns.update(PAIR_SHORT=['Py / NM', 'Py / R', 'NM / R'],
                  PAIR_NAMES=['Python vs\nNONMEM', 'Python vs\nR aghq', 'NONMEM vs\nR aghq'],
                  ROUTE_NAMES=['Python (Laplace)', 'NONMEM (Laplace)', 'R aghq (external)'])
    return ns


def case_row(registry, means, model, case_id):
    d = registry[model, case_id]
    m = means[model, case_id, 'python_laplace']
    assert m['labels'] == LABELS
    return dict(drug=model, case_id=case_id, posterior=m['posterior'], state_ids=m['state_ids'],
                labels=m['labels'], times=[o['time_h'] for o in d['observations']],
                observations=[o['concentration'] for o in d['observations']], states=d['states'],
                events=[s['dose_events'] for s in d['states']], source=m)


def panel_data(registry, means):
    scans = read(OLD / 'figure2_v2/data/panel_data.json')
    points = []
    for scan in scans:
        for row in scan['rows']:
            new = case_row(registry, means, scan['drug'], row['case_id'])
            assert row['state_ids'] == new['state_ids']
            row.update(posterior=new['posterior'], source=new['source'])
            for state, sid, value in zip(LABELS, new['state_ids'], new['posterior']):
                points.append(dict(figure=2, panel=scan['panel'], drug=scan['drug'], case_id=row['case_id'],
                    series=scan['series'], x=row['x'], state=state, state_id=sid, posterior=value))
    recipe = read(OLD / 'figures3_4_v2/data/figure_inputs.json')
    selected = copy.deepcopy(recipe['figure3'])
    for drug, group in selected.items():
        group['observations'] = [case_row(registry, means, drug, r['case_id']) for r in group['observations']]
        for p in group['priors']:
            p['case'] = case_row(registry, means, drug, p['case']['case_id'])
            q = p['p']
            expected = [(1-q)**2, q*(1-q), q*(1-q), q*q]
            assert max(abs(s['prior_probability']-v) for s,v in zip(p['case']['states'], expected)) < 1e-14
    histories = [[case_row(registry, means, r['drug'], r['case_id']) for r in pair] for pair in recipe['figure4']]
    assert [round(r['observations'][0], 3) for r in histories[0]] == [14.968, 10.476]
    assert histories[1][0]['observations'] == histories[1][1]['observations'] == [12.0]
    return scans, selected, histories, points


def comparisons(registry, means):
    data = dict(pairs={}, cases=[])
    summary = {}
    for drug in ['OXC', 'TAC']:
        data['pairs'][drug] = {}
        summary[drug] = {}
        ref = 'C003' if drug == 'OXC' else 'c003'
        data['cases'].append(case_row(registry, means, drug, ref))
        for pair, methods in PAIRS.items():
            rows = []
            for model, cid in sorted(registry):
                if model != drug or not all((model, cid, method) in means for method in methods):
                    continue
                a, b = [means[model, cid, method] for method in methods]
                assert a['state_ids'] == b['state_ids']
                left, right = a['posterior'], b['posterior']
                map_a = {s for s,v in zip(a['state_ids'], left) if v == max(left)}
                map_b = {s for s,v in zip(b['state_ids'], right) if v == max(right)}
                metrics = dict(linfinity=max(abs(x-y) for x,y in zip(left,right)), map_set_match_exact=map_a == map_b)
                rows.append(dict(case_id=cid, state_ids=a['state_ids'], left=left, right=right,
                                 metrics=metrics, description=registry[model,cid]['description']))
            data['pairs'][drug][pair] = rows
            sens = [r for r in rows if r['case_id'] != ref]
            vals = [r['metrics']['linfinity'] for r in sens]
            worst = max(sens, key=lambda r:r['metrics']['linfinity'])
            summary[drug][pair] = dict(all_pairs=len(rows), n=len(sens), minimum=min(vals),
                median=float(np.median(vals)), maximum=max(vals),
                changed=sum(not r['metrics']['map_set_match_exact'] for r in sens),
                worst_case=worst['case_id'], worst_description=worst['description'])
    assert [summary['OXC'][p]['n'] for p in PAIRS] == [82,81,81]
    assert [summary['TAC'][p]['n'] for p in PAIRS] == [133,133,133]
    return data, summary


def bounds(fig):
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()
    outside = []
    for item in fig.findobj(matplotlib.text.Text):
        if item.get_visible() and item.get_text():
            box = item.get_window_extent(renderer)
            if box.x0 < -1 or box.y0 < -1 or box.x1 > fig.bbox.width+1 or box.y1 > fig.bbox.height+1:
                outside.append(item.get_text())
    assert not outside, outside
    return dict(text_outside_canvas=outside, canvas_mm=(fig.get_size_inches()*25.4).tolist(),
                axes=[dict(xlim=list(ax.get_xlim()), ylim=list(ax.get_ylim())) for ax in fig.axes])


def save(number, fn, data):
    fig = fn(data)
    checks = bounds(fig)
    for fmt in ['eps','pdf','svg']:
        fig.savefig(output(f'artwork/Fig{number}.{fmt}'))
    fig.savefig(output(f'artwork/Fig{number}.png'), dpi=600)
    fig.savefig(output(f'artwork/Fig{number}_preview.png'), dpi=180)
    plt.close(fig)
    fig = fn(data, gray=True)
    fig.savefig(output(f'qa/Fig{number}_grayscale.png'), dpi=180)
    plt.close(fig)
    return checks


def reconcile_numeric(means, pairs):
    numeric = ROOT.parent / 'numeric'
    external = read(numeric / 'case_vectors.json')
    assert len(external) == len(means) == 650
    max_delta = 0.0
    for r in external:
        local = means[r['model'], r['scenario_id'], r['method']]
        assert set(local['state_ids']) == set(r['state_order'])
        delta = max(abs(v-r['mean_normalized_vector'][s]) for s,v in zip(local['state_ids'], local['posterior']))
        max_delta = max(max_delta, delta)
        assert delta < 1e-14
        assert local['source_sha256'] == r['source_sha256']
    external_pairs = read(numeric / 'pair_differences.json')
    inverse = {tuple(methods): key for key,methods in PAIRS.items()}
    compared = 0
    max_pair_delta = 0.0
    for row in external_pairs:
        name = inverse[row['method_a'], row['method_b']]
        local = next(r for r in pairs['pairs'][row['model']][name] if r['case_id'] == row['scenario_id'])
        delta = abs(local['metrics']['linfinity'] - row['dInf'])
        assert delta < 1e-14
        assert local['metrics']['map_set_match_exact'] == (not row['exact']['highest_changed'])
        assert row['exact']['highest_changed'] == row['tolerance']['highest_changed']
        max_pair_delta = max(max_pair_delta, delta)
        compared += 1
    write('qa/numeric_reconciliation.json', dict(groups=len(external), pairs=compared,
          max_posterior_delta=max_delta, max_pair_difference_delta=max_pair_delta,
          highest_state_exact_and_tolerance_agree=True, status='PASS'))


def legends():
    path = OLD / 'Figure1_4_图注中英文汇总_20261018.md'
    raw = path.read_bytes()
    HASHES[str(path)] = hashlib.sha256(raw).hexdigest()
    text = raw.decode('utf-8-sig').replace('\r\n', '\n').replace('\r', '\n')
    first, rest = text.split('## 图2', 1)
    _, first = first.split('## 图1', 1)
    first = first.replace('Python（Py）和NONMEM（NM）均采用Laplace近似，GHQ为Gauss-Hermite求积。',
        'Python（Py）和NONMEM（NM）采用Laplace近似；R表示通过外部R程序包aghq实现的自适应Gauss-Hermite求积。')
    first = first.replace('Python (Py) and NONMEM (NM) both use the Laplace approximation; GHQ denotes Gauss-Hermite quadrature.',
        'Python (Py) and NONMEM (NM) use the Laplace approximation; R denotes adaptive Gauss-Hermite quadrature implemented using the external R package aghq.')
    first = first.replace('GHQ相关', 'R aghq相关').replace('involving GHQ', 'involving R aghq')
    first = first.replace('比较采用五次运行的平均后验概率，敏感性场景不含参考场景。',
        '比较采用五次运行各自归一化后的平均后验概率，敏感性场景不含参考场景。')
    first = first.replace('Comparisons use mean posterior probabilities across five runs; sensitivity comparisons exclude the reference scenarios',
        'Comparisons use mean posterior probabilities after normalizing each of five runs; sensitivity comparisons exclude the reference scenarios.')
    rest = rest.replace('Values are mean posterior probabilities across five runs of the Python package\'s Laplace calculation',
        'Values are mean posterior probabilities after normalizing each of five runs of the Python package\'s Laplace calculation.')
    rest = rest.replace('图示为Python程序包Laplace计算所得的五次运行平均后验概率。',
        '图示为Python程序包Laplace计算所得的五次运行各自归一化后的平均后验概率。')
    combined = '# 图1-4中英文图注汇总\n\n更新日期：2026-10-23。沿用2026-10-18面板优先图注，仅更新计算路线、完整配对计数和五次运行口径。\n\n## 图1' + first + '## 图2' + rest
    output('Figure1_4_图注中英文汇总_20261023.md').write_text(combined, encoding='utf-8', newline='\n')
    blocks = {}
    for number in range(1,5):
        block = combined.split(f'## 图{number}\n',1)[1].split(f'## 图{number+1}\n',1)[0]
        cn, en = block.split('### 中文',1)[1].split('### English',1)
        blocks[str(number)] = dict(cn=cn.strip(), en=en.strip())
        output(f'captions/Figure{number}_图注中英文.md').write_text(f'# 图{number}\n' + block, encoding='utf-8', newline='\n')
    write('data/captions.json', blocks)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--figures', nargs='+', type=int, default=[1,2,3,4])
    args = parser.parse_args()
    registry, means, raw, exclusions = source_data()
    scans, selected, histories, points = panel_data(registry, means)
    write('data/normalized_five_run_means.json', list(means.values()))
    table('data/normalized_five_run_means.csv', list(means.values()))
    write('data/raw_diagnostics_separate.json', raw)
    write('data/exclusions.json', exclusions)
    write('data/figure2_panel_data.json', scans)
    write('data/figures3_4_inputs.json', dict(figure3=selected, figure4=histories))
    ns2 = legacy_renderer('figure2_v2/draw_figure2.py', {'style','make_figure'}, {'LABELS','STATE_NAMES','COLORS','MARKERS','STYLES'})
    ns34 = legacy_renderer('figures3_4_v2/draw_figures_3_4.py',
        {'style','palette','axis_style','label','record','draw_figure3','draw_figure4','verify_bounds'},
        {'LABELS','MATH_LABELS','NAMES','COLORS','MARKERS','STYLES','HATCHES','POINTS'})
    checks = {}
    for number, fn, inputs in [(2,ns2['make_figure'],scans),(3,ns34['draw_figure3'],selected),(4,ns34['draw_figure4'],histories)]:
        if number in args.figures:
            checks[number] = save(number, fn, inputs)
    points += ns34['POINTS']
    data1, summary = comparisons(registry, means)
    reconcile_numeric(means, data1)
    legends()
    write('data/figure1_pair_data.json', data1)
    write('data/figure1_pair_summary.json', summary)
    if 1 in args.figures:
        ns1 = legacy_renderer('figure1_v2/draw_figure1.py',
            {'scientific','gray_color','style','label','reference_panel','sensitivity_panel','make_figure'},
            {'PAIR_KEYS','PAIR_SHORT','PAIR_NAMES','ROUTE_NAMES','ROUTE_COLORS','STATE_LABELS','POINTS','TEXT'}, figure1=True)
        checks[1] = save(1, ns1['make_figure'], data1)
        points += [dict(figure=1, **p) for p in ns1['POINTS']]
    write('data/plotted_points.json', points)
    table('data/plotted_points.csv', points)
    write('qa/render_checks.json', checks)
    provenance = dict(source_sha256=HASHES, aggregation='Normalize each selected complete finite run with math.fsum, then statistics.mean over five runs; reconcile with independent numeric worker.',
        inclusion='Finite complete posterior on all candidate states across all five selected formal runs. Bridge stability/comparison_eligible flags are diagnostics, not exclusions.',
        selected_group_count=len(means), excluded_group_count=len(exclusions), summary=summary,
        raw_diagnostics='data/raw_diagnostics_separate.json', state_alignment='state_event_id; manuscript state labels checked for Figures 2-4',
        plotting='Legacy drawing functions extracted with AST; no legacy data-loading or output code executes.',
        exports='Vector EPS/PDF/SVG, 600 dpi PNG, 180 dpi previews; Arial 8 pt; original dimensions and palette.',
        no_model_reruns=True, manuscript_not_modified=True, matplotlib=matplotlib.__version__, python=sys.version)
    for path, digest in HASHES.items():
        assert hashlib.sha256(Path(path).read_bytes()).hexdigest() == digest, ('Source changed during render', path)
    write('provenance.json', provenance)
    print(json.dumps(dict(figures=args.figures, groups=len(means), exclusions=len(exclusions), summary=summary), indent=2))


if __name__ == '__main__':
    main()
