"""Read saved evidence only. All generated files stay beside this script."""

from collections import Counter
from datetime import datetime, timezone
from hashlib import sha256
from itertools import combinations
import json
import math
from pathlib import Path
import statistics
import sys

sys.dont_write_bytecode = True
WORK = Path('D:/AI-ready PMX benchmark engine')
BASE = WORK / 'manuscript_revision_execution_20260928/48_final_validation_redesign_20261005'
SUP = BASE / 'parallel_delivery_20261018/02_submission_materials/supplement_scaffold_20261020'
OUT = Path(__file__).resolve().parent
assert OUT == BASE / 'delivery_updates/fullresults_figures_20261023/numeric'
METHODS = ('python_laplace', 'nonmem_laplace', 'r_aghq')
HASHES = {}
COUNTS = Counter()


def read(path, expected=None, parse=True):
    path = Path(path).resolve()
    assert path.is_relative_to(WORK), path
    raw = path.read_bytes()
    digest = sha256(raw).hexdigest()
    if expected is not None:
        assert digest == expected.lower(), ('hash mismatch', str(path))
    HASHES[path.relative_to(WORK).as_posix()] = digest
    return json.loads(raw) if parse else raw


def normalize(vector, keys):
    assert isinstance(vector, dict) and set(vector) == set(keys)
    assert all(type(v) in (int, float) and math.isfinite(v) and 0 <= v <= 1 for v in vector.values())
    total = math.fsum(vector.values())
    assert abs(total - 1) <= 1e-6
    return {k: vector[k] / total for k in keys}


def summarize(vectors, keys):
    normalized = [normalize(v, keys) for v in vectors]
    mean = {k: statistics.mean(v[k] for v in normalized) for k in keys}
    fields = {}
    for prefix, data in [('raw', vectors), ('normalized', normalized)]:
        sd = {k: statistics.stdev(v[k] for v in data) for k in keys}
        span = {k: max(v[k] for v in data) - min(v[k] for v in data) for k in keys}
        fields[prefix + '_max_sample_sd'] = max(sd.values())
        fields[prefix + '_max_range'] = max(span.values())
        fields[prefix + '_state_sample_sd'] = sd
        fields[prefix + '_state_range'] = span
    return mean, normalized, fields


def distribution(v):
    ordered = sorted(v.values(), reverse=True)
    return {'Pmax': ordered[0], 'HN': min(1., max(0., -math.fsum(p * math.log(p) for p in ordered if p) / math.log(len(v)))),
            'top_two_gap': ordered[0] - ordered[1]}


def groups(v, tolerance):
    result = []
    for k in sorted(v, key=lambda k: (-v[k], k)):
        if not result or v[result[-1][0]] - v[k] > tolerance:
            result.append([k])
        else:
            result[-1].append(k)
    return result


def compare(a, b):
    assert set(a) == set(b)
    diffs = {k: abs(a[k] - b[k]) for k in a}
    result = {'dInf': max(diffs.values()), 'dInf_states': [k for k in a if diffs[k] == max(diffs.values())],
              'TV': math.fsum(diffs.values()) / 2,
              'd2': math.sqrt(math.fsum(v * v for v in diffs.values())),
              'dH': math.sqrt(math.fsum((math.sqrt(a[k]) - math.sqrt(b[k])) ** 2 for k in a) / 2),
              'state_absolute_differences': diffs}
    for name, tol in [('exact', 0), ('tolerance', 1e-6)]:
        ga, gb = groups(a, tol), groups(b, tol)
        result[name] = {'highest_changed': set(ga[0]) != set(gb[0]),
                        'full_order_changed': [set(g) for g in ga] != [set(g) for g in gb],
                        'groups_a': ga, 'groups_b': gb}
    return result


def p95(values):
    ordered = sorted(values)
    i = .95 * (len(values) - 1)
    low, high = math.floor(i), math.ceil(i)
    return ordered[low] + (i - low) * (ordered[high] - ordered[low])


def pair_summary(rows):
    if not rows:
        return {'n': 0}
    vals = [r['dInf'] for r in rows]
    out = {'n': len(rows), 'median_dInf': statistics.median(vals), 'p95_supplement': None,
           'p95_linear_audit': p95(vals), 'max_dInf': max(vals),
           'max_scenarios': [r['scenario_id'] for r in rows if r['dInf'] == max(vals)],
           'count_dInf_le_001': sum(v <= .01 for v in vals), 'count_dInf_le_005': sum(v <= .05 for v in vals)}
    out['distance_metrics'] = {metric: {
        'n': len(rows), 'median': statistics.median(r[metric] for r in rows),
        'p95_supplement': None, 'p95_linear_provisional': p95([r[metric] for r in rows]),
        'max': max(r[metric] for r in rows),
        'max_scenarios': [r['scenario_id'] for r in rows if r[metric] == max(x[metric] for x in rows)]}
        for metric in ('dInf', 'TV', 'd2', 'dH')}
    for name in ('exact', 'tolerance'):
        out[name] = {field: [r['scenario_id'] for r in rows if r[name][field]]
                     for field in ('highest_changed', 'full_order_changed')}
        out[name].update({field + '_n': len(out[name][field]) for field in ('highest_changed', 'full_order_changed')})
    changed = [r for r in rows if r['tolerance']['highest_changed']]
    out['changed_top_distribution'] = {method: {
        'Pmax_max': max(r['distribution'][method]['Pmax'] for r in changed),
        'HN_min': min(r['distribution'][method]['HN'] for r in changed)}
        for method in (rows[0]['method_a'], rows[0]['method_b'])} if changed else {}
    return out


def mapped(vector, states):
    mapping = {s['state_id']: s['state_event_id'] for s in states}
    return {mapping.get(k, k): v for k, v in vector.items()}


def ref_read(ref):
    return read(SUP / ref['path'], ref['sha256'])


def verify_r(run, design, vector):
    evidence = run['evidence_files']
    output = run.get('output') or next(e for e in evidence if e.get('original_path', '').endswith('/result.json'))
    result = ref_read(output)
    receipt = ref_read(run['receipt'])
    assert result['status'] == 'success'
    assert result['stability_passed'] == run['stability_passed']
    assert mapped(result['posterior'], design['states']) == vector
    inp = result['input']
    assert receipt['input_sha256'] == design['input_source_sha256'] == inp['source_sha256']
    keys = [s['state_event_id'] for s in design['states']]
    assert set(inp['state_ids']) == set(keys)
    for state in design['states']:
        k = state['state_event_id']
        assert abs(inp['priors'][k] - state['prior_probability']) < 1e-14
        assert [(e['time'], e['amount']) for e in inp['events'][k]] == [(e['time_h'], e['amount_mg']) for e in state['dose_events']]
    assert len(inp['observations']) == len(design['observations'])
    for a, b in zip(inp['observations'], design['observations']):
        assert abs(a['time'] - b['time_h']) < 1e-10 and abs(a['value'] - b['concentration']) < 1e-10
    boundary = design['model'] == 'TAC' and design['scenario_id'] in ('c107', 'c110')
    if boundary:
        assert all(o.get('event_phase') == 'before_events' for o in inp['observations'])
        assert 'rerun_tac_boundary_20261022/' in run['run_id']
    COUNTS['r_raw_results_and_receipts_verified'] += 1
    return {'result': output, 'receipt': run['receipt'], 'input_sha256': receipt['input_sha256'],
            'observation_event_phases': [o.get('event_phase') for o in inp['observations']],
            'boundary_repaired_input_verified': True if boundary else None}


def main():
    designs = read(SUP / 'authoring/data/designs.json')
    registry = read(SUP / 'authoring/data/results.json')
    diagnostics = read(SUP / 'authoring/data/diagnostics.json')
    manifests = read(SUP / 'authoring/data/run_manifests.json')
    definitions = read(SUP / 'authoring/diagnostic_definitions.json')
    read(SUP / 'tools/diagnostics.py', parse=False)
    read(SUP / 'tools/intake_metrics.py', parse=False)
    read(Path(__file__), parse=False)
    dmap = {(d['model'], d['scenario_id']): d for d in designs}
    diagmap = {(d['model'], d['scenario_id']): d for d in diagnostics}
    mmap = {m['manifest_id']: m for m in manifests}
    assert definitions['percentile_method'] is None
    cases, exclusions, boundary = [], [], []
    for rec in registry:
        if rec['method'] not in METHODS:
            continue
        model, cid, method = rec['model'], rec['scenario_id'], rec['method']
        d = dmap[model, cid]
        source = read(SUP / rec['source_path'], rec['source_sha256']) if rec.get('source_path') else {}
        all_runs = source.get('case', {}).get('runs', source.get('run_evidence', []))
        runs = [r for r in all_runs if r.get('selected_for_summary')]
        if len(runs) != 5:
            exclusions.append({'model': model, 'scenario_id': cid, 'method': method,
                               'selected_runs': len(runs), 'status': rec['status'], 'reason': 'not_five_selected_runs',
                               'source_path': rec.get('source_path'), 'source_sha256': rec.get('source_sha256')})
            continue
        runs.sort(key=lambda r: r['repetition'])
        assert {r['repetition'] for r in runs} == set(range(1, 6))
        assert all(r['phase'] == 'formal' for r in runs)
        assert [r['run_id'] for r in runs] == rec['run_ids']
        assert rec['n_runs'] == 5 and rec['design_fingerprint'] == d['design_fingerprint']
        manifest = mmap[rec['run_manifest_id']]
        assert manifest['run_ids'] == rec['run_ids'] and manifest['design_fingerprint'] == d['design_fingerprint']
        keys = [s['state_event_id'] for s in d['states']]
        raw = [mapped(r['raw_probabilities'], d['states']) for r in runs]
        mean, normalized, repeat = summarize(raw, keys)
        assert mean == rec['values'], (model, cid, method, 'registry mean')
        stored = diagmap[model, cid]['routes'][method]['summary']
        assert repeat['normalized_max_sample_sd'] == stored['max_sd_after_normalization']
        assert repeat['normalized_max_range'] == stored['max_range_after_normalization']
        assert abs(distribution(mean)['HN'] - stored['normalized_entropy']) < 1e-15
        provenance = []
        for run, v in zip(runs, raw):
            item = {k: run.get(k) for k in ('run_id', 'repetition', 'phase', 'selected_for_summary', 'stability_passed', 'outcome')}
            if method == 'r_aghq':
                item.update(verify_r(run, d, v))
            provenance.append(item)
        row = {'model': model, 'scenario_id': cid, 'role': d['role'], 'category': d['category'],
               'category_title': d['category_title'],
               'description': d['description'], 'method': method, 'n_runs': 5,
               'design_fingerprint': d['design_fingerprint'], 'input_source_sha256': d['input_source_sha256'],
               'state_order': keys, 'state_labels': {s['state_event_id']: s['state_id'] for s in d['states']},
               'mean_normalized_vector': mean, 'normalized_run_vectors': normalized,
               'distribution': distribution(mean), 'repeatability': repeat,
               'source_path': rec['source_path'], 'source_sha256': rec['source_sha256'],
               'run_manifest_id': rec['run_manifest_id'], 'selected_runs': provenance,
               'raw_registry_comparison_eligible': rec.get('comparison_eligible', True),
               'audit_included': True, 'raw_stability_passed': [r.get('stability_passed') for r in runs]}
        cases.append(row)
        if model == 'TAC' and cid in ('c107', 'c110'):
            boundary.append(row)
    indexed = {(r['model'], r['scenario_id'], r['method']): r for r in cases}
    pairs = []
    for d in designs:
        for a, b in combinations(METHODS, 2):
            ra = indexed.get((d['model'], d['scenario_id'], a))
            rb = indexed.get((d['model'], d['scenario_id'], b))
            if ra is None or rb is None:
                continue
            pairs.append({'model': d['model'], 'scenario_id': d['scenario_id'], 'role': d['role'],
                          'category': d['category'], 'category_title': d['category_title'],
                          'description': d['description'], 'method_a': a, 'method_b': b,
                          'distribution': {a: ra['distribution'], b: rb['distribution']},
                          'source_sha256_a': ra['source_sha256'], 'source_sha256_b': rb['source_sha256'],
                          **compare(ra['mean_normalized_vector'], rb['mean_normalized_vector'])})
    summary = {'as_of_utc': datetime.now(timezone.utc).isoformat(),
               'policy': {'required_selected_runs': 5, 'stability_flag_excludes': False,
                          'raw_probability_sum_tolerance': 1e-6, 'ranking_tolerance': 1e-6,
                          'ranking_rule': 'group maximum anchor; exact and tolerance results both retained',
                          'aggregation': 'normalize each run, then arithmetic mean over five selected runs',
                          'repeatSD': 'maximum statewise sample SD, ddof=1',
                          'percentile_method_in_actual_supplement': None,
                          'p95_supplement': 'Unavailable: configured null, not linear',
                          'p95_linear_audit': 'Provisional only, pending user adoption of type 7 / linear: x[floor(.95*(n-1))] plus fractional interpolation. Not a preexisting supplement convention.'},
               'models': {}, 'exclusions': exclusions, 'checks': dict(COUNTS)}
    for model in ('OXC', 'TAC'):
        entry = {'routes': {}, 'pairs': {}}
        for method in METHODS:
            rows = [r for r in cases if r['model'] == model and r['method'] == method]
            entry['routes'][method] = {
                'reference_n': sum(r['role'] == 'reference' for r in rows),
                'sensitivity_n': sum(r['role'] != 'reference' for r in rows),
                'raw_stability_flag_counts_selected_runs': dict(Counter(str(v) for r in rows for v in r['raw_stability_passed'])),
                'five_stability_passes_cases': [r['scenario_id'] for r in rows if all(v is True for v in r['raw_stability_passed'])],
                'included_despite_raw_registry_ineligibility': [r['scenario_id'] for r in rows if not r['raw_registry_comparison_eligible']],
                'max_repeatSD': max(r['repeatability']['normalized_max_sample_sd'] for r in rows),
                'max_repeatRange': max(r['repeatability']['normalized_max_range'] for r in rows)}
        for a, b in combinations(METHODS, 2):
            rows = [r for r in pairs if r['model'] == model and (r['method_a'], r['method_b']) == (a, b)]
            entry['pairs'][a + '__' + b] = {
                'reference': [r for r in rows if r['role'] == 'reference'],
                'sensitivity': pair_summary([r for r in rows if r['role'] != 'reference']),
                'by_category': {str(c): pair_summary([r for r in rows if r['role'] != 'reference' and r['category'] == c]) for c in range(1, 7)}}
        summary['models'][model] = entry
    provisional_path = BASE / 'delivery_updates/objective_results_update_20261023/r_aghq_two_rounds.json'
    provisional = read(provisional_path)
    deltas = []
    provisional_raw_verified = 0
    for row in provisional['rows']:
        if not row.get('vectors'):
            continue
        final = indexed['TAC', row['scenario'], 'r_aghq']
        for i, src in enumerate(row['sources']):
            result = read(src['result_path'], src['result_sha256'])
            assert normalize(result['posterior'], final['state_order']) == final['normalized_run_vectors'][i]
            provisional_raw_verified += 1
        deltas.append({'scenario_id': row['scenario'],
                       'mean_vector_dInf_final_minus_provisional': compare(final['mean_normalized_vector'], row['vectors']['r_aghq'])['dInf']})
    summary['final_vs_provisional'] = {
        'provisional_source': str(provisional_path.relative_to(WORK)), 'provisional_runs': 2, 'final_runs': 5,
        'provisional_raw_results_hash_verified': provisional_raw_verified, 'compared_cases': len(deltas),
        'max_vector_dInf': max(r['mean_vector_dInf_final_minus_provisional'] for r in deltas),
        'nonzero_cases': [r for r in deltas if r['mean_vector_dInf_final_minus_provisional'] != 0],
        'pairs': {}}
    for method in ('python_laplace', 'nonmem_laplace'):
        old = provisional['sensitivity'][method]
        new = summary['models']['TAC']['pairs'][method + '__r_aghq']['sensitivity']
        summary['final_vs_provisional']['pairs'][method] = {
            'n_old': old['n'], 'n_new': new['n'], 'median_dInf_delta': new['median_dInf'] - old['median_dinf'],
            'max_dInf_delta': new['max_dInf'] - old['max_dinf'],
            'highest_changed_lists_equal': old['highest_changed'] == new['tolerance']['highest_changed'],
            'full_order_changed_lists_equal': old['full_rank_changed'] == new['tolerance']['full_order_changed']}
    summary['old_oxc_gate_vs_user_policy'] = {'old_source': str(provisional_path.relative_to(WORK)),
        'old': provisional['OXC_completed_five_run_aghq']['pairs'],
        'new_sensitivity_n': summary['models']['OXC']['routes']['r_aghq']['sensitivity_n']}
    objective_diffs = {'TAC_final_vs_two_run_provisional': summary['final_vs_provisional'], 'OXC_policy_change': {}}
    for method in ('python_laplace', 'nonmem_laplace'):
        old = provisional['OXC_completed_five_run_aghq']['pairs'][method]
        new = summary['models']['OXC']['pairs'][method + '__r_aghq']['sensitivity']
        objective_diffs['OXC_policy_change'][method] = {
            'added_sensitivity_cases': ['C023', 'C024', 'C025'], 'excluded_no_vector': ['C026'],
            'n_old': old['sensitivity_n'], 'n_new': new['n'],
            'median_dInf_old': old['sensitivity_median_dinf'], 'median_dInf_new': new['median_dInf'],
            'median_dInf_delta': new['median_dInf'] - old['sensitivity_median_dinf'],
            'max_dInf_old': old['sensitivity_max']['maximum_absolute_difference'], 'max_dInf_new': new['max_dInf'],
            'max_scenario_old': old['sensitivity_max']['scenario'], 'max_scenarios_new': new['max_scenarios'],
            'highest_changed': new['tolerance']['highest_changed'], 'full_order_changed': new['tolerance']['full_order_changed']}
    mc = [r for r in registry if r['method'] == 'virtual_patient_mc']
    mc_snapshot = {model: {
        'status_counts': dict(Counter(r['status'] for r in mc if r['model'] == model)),
        'displayed_sensitivity': sum(r['display_approved'] and dmap[model, r['scenario_id']]['role'] != 'reference' for r in mc if r['model'] == model),
        'displayed_reference': sum(r['display_approved'] and dmap[model, r['scenario_id']]['role'] == 'reference' for r in mc if r['model'] == model),
        'n_runs_counts': dict(Counter(str(r['n_runs']) for r in mc if r['model'] == model))} for model in ('OXC', 'TAC')}
    mcroot = WORK / 'outputs/MC_Laplace_concentration_comparisons_20261022'
    mc_execution = read(mcroot / 'compute/execution_summary.json')
    mc_delivery = read(mcroot / 'audit/delivery_checks.json')
    mc_inventory = read(SUP / 'authoring/coverage_sources/web_mc_inventory.json')
    for rel in ('README.md', 'audit/verification_notes.md'):
        read(mcroot / rel, parse=False)
    mc_status = {
        'as_of_utc': summary['as_of_utc'], 'scope': 'Saved MC status only; no MC recalculation, inclusion change or interpretive rewrite.',
        'registry_snapshot': mc_snapshot,
        'archived_web_output_cases': mc_inventory['archived_case_count'],
        'archived_web_sensitivity_cases': mc_inventory['sensitivity_count'],
        'curve_comparison_collection': {k: mc_execution[k] for k in (
            'created_utc', 'audited_groups', 'planned_points', 'successful_points', 'failed_point_count',
            'case_count', 'formal_anchors', 'reverse_equality_pairs', 'exact_grid_validation_comparisons',
            'failed_concentrations_by_group', 'scientific_code_changed')},
        'curve_collection_figure_count': mc_delivery['figure_count'],
        'source_status_notes': [
            '37 displayed OXC posterior vectors (1 reference + 36 sensitivity), one reported web output each; 44 archived web cases (1 + 43).',
            'Seven excluded OXC web outputs remain excluded: C031/C032/C083 sum-to-one mismatch; C065-C068 candidate/prior mismatch.',
            'No TAC MC vectors are entered in the current supplement.',
            '44 curve figures and 31 Python concentration-scan groups are complete; these are distinct from five-repeat scenario experiments.',
            'MC curve coordinates and individual virtual-patient samples are unavailable; deployed model and estimator equivalence remain unverified.',
            'Relevant remaining evidence boundaries for the main question 2/3 follow-up are recorded above. No claim that their interpretation or wording is resolved.'
        ]}
    summary['mc_status_file'] = 'mc_status.json'
    assert summary['models']['OXC']['routes']['r_aghq']['sensitivity_n'] == 81
    assert summary['models']['TAC']['routes']['r_aghq']['sensitivity_n'] == 133
    # Ensure an actively edited registry did not change partway through this audit.
    mismatches = [rel for rel, digest in HASHES.items() if sha256((WORK / rel).read_bytes()).hexdigest() != digest]
    assert not mismatches, mismatches
    summary['checks']['source_files_hash_verified_and_unchanged'] = len(HASHES)
    compact = {'as_of_utc': summary['as_of_utc'], 'policy': summary['policy'], 'checks': summary['checks'],
               'routes': [{'model': m, 'method': method, **{k: r[k] for k in ('reference_n', 'sensitivity_n', 'max_repeatSD', 'max_repeatRange', 'raw_stability_flag_counts_selected_runs')}}
                          for m, entry in summary['models'].items() for method, r in entry['routes'].items()],
               'sensitivity': [{'model': m, 'pair': pair, 'n': r['sensitivity']['n'],
                                'distances': r['sensitivity']['distance_metrics'],
                                'highest_changed_n': r['sensitivity']['tolerance']['highest_changed_n'],
                                'full_order_changed_n': r['sensitivity']['tolerance']['full_order_changed_n']}
                               for m, entry in summary['models'].items() for pair, r in entry['pairs'].items()],
               'reference': [{k: r[k] for k in ('model', 'scenario_id', 'method_a', 'method_b', 'dInf', 'TV', 'd2', 'dH', 'distribution')}
                             for r in pairs if r['role'] == 'reference'],
               'files': {'case_vectors': 'case_vectors.json', 'pairs': 'pair_differences.json', 'category_summaries': 'summary.json',
                         'objective_diffs': 'objective_diffs.json', 'mc_status_separate': 'mc_status.json', 'source_hashes': 'source_hashes.json'}}
    products = {'compact.json': compact, 'summary.json': summary, 'case_vectors.json': cases, 'pair_differences.json': pairs,
                'changed_top_cases.json': [r for r in pairs if r['tolerance']['highest_changed']],
                'boundary_c107_c110.json': boundary, 'mc_status.json': mc_status, 'objective_diffs.json': objective_diffs,
                'source_hashes.json': HASHES}
    for name, value in products.items():
        (OUT / name).write_text(json.dumps(value, ensure_ascii=True, indent=2, allow_nan=False) + '\n', encoding='utf-8')
    hashes = {name: sha256((OUT / name).read_bytes()).hexdigest() for name in products}
    (OUT / 'output_hashes.json').write_text(json.dumps(hashes, indent=2) + '\n', encoding='utf-8')
    print(json.dumps({'checks': summary['checks'], 'case_route_rows': len(cases), 'pair_rows': len(pairs),
                      'files': list(products), 'final_vs_provisional_max_vector_difference': summary['final_vs_provisional']['max_vector_dInf']}))


if __name__ == '__main__':
    main()
