import json
import os
from pathlib import Path

ROOT = Path(".")

INPUT_MAIN = ROOT / "results" / "row20_h0_attribution" / "row20_thin_slice_attribution.json"
INPUT_LA = ROOT / "results" / "row20_h0_attribution" / "row20_lA_probe.json"
INPUT_SN = ROOT / "results" / "row20_h0_attribution" / "row20_SN_probe.json"
INPUT_SN_GEOM = ROOT / "results" / "row20_h0_attribution" / "row20_SN_geometry_probe.json"
INPUT_SN_OFFSET = ROOT / "results" / "row20_h0_attribution" / "row20_SN_offset_probe.json"
INPUT_BAO = ROOT / "results" / "row20_h0_attribution" / "row20_BAO_bridge_probe.json"

OUTPUT_JSON = ROOT / "results" / "row20_h0_attribution" / "row20_H0_layered_report.json"
OUTPUT_REPORT = ROOT / "results" / "row20_h0_attribution" / "row20_H0_layered_report.md"


def load(path):
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def main():
    main_data = load(INPUT_MAIN)
    la = load(INPUT_LA)
    sn = load(INPUT_SN)
    sn_geom = load(INPUT_SN_GEOM)
    sn_offset = load(INPUT_SN_OFFSET)
    bao = load(INPUT_BAO)

    # Extract key metrics
    ellA = la["ell_A"]
    sn_node = sn["SN_node"]
    sn_geom_data = sn_geom["midpoint_geometry"]
    sn_offset_data = sn_offset["pivot_geometry"]
    bao_data = bao["z_0_706_projection"]

    summary = {
        "CMB_lA": {
            "pull_sigma": ellA["diag_pull_sigma"],
            "fractional_shift": ellA["fractional_required_shift"],
            "role": "early_universe_anchor"
        },
        "SN_midpoint": {
            "pull_sigma": sn_node["diag_pull_sigma"],
            "fractional_shift": sn_node["fractional_shift"],
            "pivot_curvature_sigma": sn_geom_data["midpoint_pull_curvature"],
            "pivot_survives_offset": abs(sn_offset_data["global_recentered_pivot_pull"]) > 2,
            "role": "late_distance_curvature"
        },
        "BAO_bridge": {
            "H_pull": bao_data["H"]["pull"],
            "DM_pull": bao_data["D_M"]["pull"],
            "pull_gap": bao_data["pull_gap_H_minus_DM"],
            "role": "intermediate_projection_bridge"
        },
        "SH0ES": main_data["totals"]["SH0ES_overlay"]
    }

    interpretation = []

    interpretation.append(
        "The H0 tension decomposes into three layers: early-universe acoustic anchoring (CMB ℓ_A), intermediate BAO projection geometry, and late-universe SN distance curvature."
    )

    interpretation.append(
        "CMB ℓ_A is a high-significance anchor requiring only ~0.13% shift to eliminate its residual, indicating extreme sensitivity to compressed representation."
    )

    if summary["SN_midpoint"]["pivot_survives_offset"]:
        interpretation.append(
            "SN midpoint residual at z=0.35 forms a curvature pivot that survives global offset removal, indicating intrinsic geometry rather than simple calibration shift."
        )

    if abs(summary["BAO_bridge"]["pull_gap"]) > 2:
        interpretation.append(
            "BAO z≈0.706 shows a radial/transverse projection split, indicating internal bridge stress rather than a unified expansion solution."
        )

    interpretation.append(
        "SH0ES represents a high-side overlay that amplifies, but does not solely create, the late-universe tension."
    )

    interpretation.append(
        "The tension is therefore layered and geometric, not attributable to a single parameter mismatch."
    )

    result = {
        "signature": "ROW20_H0_LAYERED_TENSION_REPORT_v1",
        "context": "DIAGNOSTIC_NON_GATING",
        "summary": summary,
        "interpretation": interpretation,
        "verdict": (
            "H0_layered_tension_structure_identified; "
            "no physics, thresholds, datasets, parameters, or gate verdict changes."
        )
    }

    OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)

    with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
        json.dump(result, f, indent=2)

    with open(OUTPUT_REPORT, "w", encoding="utf-8") as f:
        f.write("# UTFANSWF v21 — H₀ Layered Tension Report\n\n")
        f.write("**Context:** DIAGNOSTIC_NON_GATING\n\n")

        f.write("## Summary\n\n")
        f.write("| Layer | Key Feature | Value |\n")
        f.write("|---|---|---:|\n")
        f.write(f"| CMB ℓ_A | pull σ | {summary['CMB_lA']['pull_sigma']:.3f} |\n")
        f.write(f"| SN z=0.35 | pull σ | {summary['SN_midpoint']['pull_sigma']:.3f} |\n")
        f.write(f"| SN pivot curvature | σ | {summary['SN_midpoint']['pivot_curvature_sigma']:.3f} |\n")
        f.write(f"| BAO H-D_M gap | σ | {summary['BAO_bridge']['pull_gap']:.3f} |\n")
        f.write(f"| SH0ES | pull σ | {summary['SH0ES']['pull_sigma']:.3f} |\n")

        f.write("\n## Interpretation\n\n")
        for item in interpretation:
            f.write(f"- {item}\n")

        f.write("\n## Verdict\n\n")
        f.write(result["verdict"] + "\n")

    print("Wrote:")
    print(os.path.abspath(OUTPUT_JSON))
    print(os.path.abspath(OUTPUT_REPORT))
    print()
    print("H0 layered tension summary:")
    print(f"CMB ℓ_A pull = {summary['CMB_lA']['pull_sigma']:.3f} σ")
    print(f"SN pivot = {summary['SN_midpoint']['pivot_curvature_sigma']:.3f} σ")
    print(f"BAO gap = {summary['BAO_bridge']['pull_gap']:.3f} σ")
    print(f"SH0ES = {summary['SH0ES']['pull_sigma']:.3f} σ")


if __name__ == "__main__":
    main()