from __future__ import annotations
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def load(rel: str):
    return json.loads((ROOT / rel).read_text(encoding='utf-8'))


def run():
    r19 = load('results/row19_results.json')
    r21 = load('results/row21_axion/result.json')
    r23 = load('results/row23_ringdown/result.json')
    r25 = load('results/row25_stress/result.json')
    allres = load('results/results.json')

    g = r19['gravity_scalar_gw']
    t = g['canonical_tensor_map']
    flrw = t['nonstationary_FLRW']
    uni = t['global_response_universality']
    tt = t['tensor_quantities']
    bnd = t['row23_boundary']
    rows = allres.get('results', [])

    checks = {
        'row19_pass': r19.get('verdict') == 'PASS',
        'row21_axion_gate_remains_independent_pass': r21.get('verdict') == 'PASS',
        'row23_canonical_zero_echo_pass': r23.get('verdict') == 'PASS' and bnd.get('R_NZH_amplitude') == 0.0,
        'legacy_axion_echo_scalar_equality_replaced': uni.get('disposition') == 'REPLACE_DIRECT_SCALAR_CHANNEL_EQUALITY_WITH_OPERATOR_PROJECTION_UNIVERSALITY',
        'operator_projection_repair_is_algebraically_consistent': all(uni.get('checks', {}).values()),
        'canonical_alpha1_zero': tt.get('alpha1_preferred_frame') == 0.0,
        'canonical_cT_exactly_one': tt.get('cT_squared') == 1.0,
        'canonical_mT_zero': tt.get('mT_squared') == 0.0,
        'canonical_FLRW_friction_form_closed': str(flrw.get('closure', '')).startswith('FUNCTIONAL_FORM_CLOSED'),
        'Mstar_and_nu_owned_by_scalaron': ('m_s^2' in flrw.get('scalaron_ownership', '') and 'not independent GW knobs' in flrw.get('scalaron_ownership', '')),
        'row25_pass': r25.get('verdict') == 'PASS',
        'row25_no_canonical_echo_open_requirement': any('canonical echo-amplitude channel is closed at zero' in x for x in r25.get('open_boundaries', [])),
        'full_suite_18_of_18_pass': len(rows) == 18 and all(x.get('verdict') == 'PASS' for x in rows),
    }

    return {
        'artifact': 'UTFANSWF_V23_PRE_PDF_GLOBAL_CROSS_SECTOR_CLOSURE_v1',
        'verdict': 'PASS_PRE_PDF_GLOBAL_CROSS_SECTOR_CLOSURE' if all(checks.values()) else 'FAIL',
        'checks': checks,
        'closed': {
            'axion_echo': 'Direct scalar R_a=R_echo equality retired; universal response is operator-level and observables are channel projections. Row21 does not inherit zero TT reflectivity.',
            'canonical_ppn_gw_tensor': 'alpha1=0, cT^2=1, mT^2=0 on canonical no-preferred-frame EH+R2 branch.',
            'gw_flrw_friction': 'Mstar^2=M_Pl^2[1+R/(3m_s^2)], nu=-(1+z)Rprime/(3m_s^2+R), dL_GW/dL_EM=sqrt([1+R0/(3m_s^2)]/[1+Rz/(3m_s^2)]).',
            'canonical_echo': 'R_NZH=0, epsilon1=0, Upsilon=0.',
            'row25_echo_stress': 'Canonical echo detection is not required; nonzero reflective branch is optional/noncanonical.',
            'parameter_reduction': 'Mstar and nu are not independent: both are owned by scalaron mass m_s. cT and mT are fixed, not scanned.',
        },
        'remaining_boundaries': {
            'scalaron_numeric': 'Numerical IR m_s is not source-completely selected in current v23 materials.',
            'generalized_gravity': 'R_mn R^mn and nonminimal phi R generalized FRG remain source-incomplete and are not needed by the canonical branch.',
            'nonzero_echo': 'Requires a new independently derived dynamical boundary response; not canonical.',
            'row25_historical': 'Historical joint CCG and CIG uncertainty-width subtests lack source-complete estimators/logs.',
            'axion_coverage': 'Shipped direct exclusion table covers 10-60 ueV, not the full declared 6-60 ueV band.',
        },
        'production_note': 'Integrated into the Aug. 20 reproducibility-side revision; protected main.tex/main.pdf unchanged.',
    }


if __name__ == '__main__':
    out = run()
    p = ROOT / 'results' / 'pre_pdf_global_cross_sector_closure_v1.json'
    p.write_text(json.dumps(out, indent=2, sort_keys=True), encoding='utf-8')
    print(json.dumps(out, indent=2, sort_keys=True))
