import json
import math
import os
from pathlib import Path

ROOT = Path(".")

INPUT_MAIN = ROOT / "results" / "row20_h0_attribution" / "row20_thin_slice_attribution.json"
INPUT_SIGN = ROOT / "results" / "row20_h0_attribution" / "row20_layered_sign_consistency.json"

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


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


def chi2_from_pulls(pulls):
    return sum(p * p for p in pulls)


def rss(pulls):
    return math.sqrt(sum(p * p for p in pulls))


def main():
    main_data = load(INPUT_MAIN)
    sign_data = load(INPUT_SIGN)

    residuals = sign_data["residuals"]

    early_radial = [
        residuals["CMB_ell_A"],
        residuals["BAO_H_z0_706"],
    ]

    late_transverse = [
        residuals["BAO_D_M_z0_706"],
        residuals["SN_pivot"],
        residuals["SH0ES_overlay"],
    ]

    all_key = early_radial + late_transverse

    early_chi2 = chi2_from_pulls(early_radial)
    late_chi2 = chi2_from_pulls(late_transverse)
    total_layered_chi2 = chi2_from_pulls(all_key)

    early_rss = rss(early_radial)
    late_rss = rss(late_transverse)
    total_rss = rss(all_key)

    sign_score = sign_data["score"]
    sign_max = sign_data["max_score"]
    sign_fraction = sign_score / sign_max

    # Null sign probability:
    # Given 5 nonzero residuals, probability of exactly this two-sided grouped sign pattern
    # under random independent signs is 1 / 2^(5-1) if global sign flip is considered equivalent.
    # This is only a heuristic diagnostic, not a formal p-value.
    sign_pattern_probability_equiv_flip = 1 / (2 ** (5 - 1))

    interpretation = []

    interpretation.append(
        "This strength test quantifies whether the layered sign pattern is strong enough to support formal attribution."
    )

    if sign_score == sign_max:
        interpretation.append(
            "All layered sign checks passed, supporting a coherent early/radial versus late/transverse split."
        )

    if early_rss >= 4 and late_rss >= 5:
        interpretation.append(
            "Both sides of the split are independently strong: early/radial RSS exceeds 4 sigma and late/transverse RSS exceeds 5 sigma."
        )

    if total_rss >= 7:
        interpretation.append(
            "The combined layered residual strength exceeds 7 sigma in RSS diagnostic magnitude."
        )

    interpretation.append(
        "This does not prove a numerical H0 reconciliation; it supports a formal attribution claim that the tension is layered rather than single-parameter."
    )

    if sign_score == sign_max and early_rss >= 4 and late_rss >= 5 and total_rss >= 7:
        status = "formal_layered_attribution_supported"
    elif sign_score >= 4 and total_rss >= 6:
        status = "formal_layered_attribution_plausible"
    else:
        status = "formal_layered_attribution_not_yet_supported"

    result = {
        "signature": "ROW20_LAYERED_ATTRIBUTION_STRENGTH_v1_NATIVE_DIAGNOSTIC",
        "context": "DIAGNOSTIC_NON_GATING",
        "rules": main_data.get("rules", {}),
        "layer_groups": {
            "early_radial": {
                "nodes": ["CMB_ell_A", "BAO_H_z0_706"],
                "pulls": early_radial,
                "chi2_sum": early_chi2,
                "rss_sigma": early_rss,
            },
            "late_transverse": {
                "nodes": ["BAO_D_M_z0_706", "SN_pivot", "SH0ES_overlay"],
                "pulls": late_transverse,
                "chi2_sum": late_chi2,
                "rss_sigma": late_rss,
            },
            "combined_key_layered_residuals": {
                "pulls": all_key,
                "chi2_sum": total_layered_chi2,
                "rss_sigma": total_rss,
            },
        },
        "sign_consistency": {
            "score": sign_score,
            "max_score": sign_max,
            "fraction": sign_fraction,
            "heuristic_random_sign_probability_equiv_global_flip": sign_pattern_probability_equiv_flip,
        },
        "interpretation": interpretation,
        "verdict": (
            f"{status}; diagnostic only; no physics, thresholds, datasets, "
            "parameters, or gate verdicts changed."
        ),
    }

    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 — Row 20 Layered Attribution Strength\n\n")
        f.write("**Context:** DIAGNOSTIC_NON_GATING. No physics, thresholds, datasets, parameters, or gate verdicts changed.\n\n")

        f.write("## Layer groups\n\n")
        f.write("| Group | Nodes | chi2 sum | RSS sigma |\n")
        f.write("|---|---|---:|---:|\n")
        f.write(
            f"| early/radial | CMB ell_A + BAO H(z=0.706) | "
            f"{early_chi2:.6f} | {early_rss:.6f} |\n"
        )
        f.write(
            f"| late/transverse | BAO D_M(z=0.706) + SN pivot + SH0ES | "
            f"{late_chi2:.6f} | {late_rss:.6f} |\n"
        )
        f.write(
            f"| combined | all five key residuals | "
            f"{total_layered_chi2:.6f} | {total_rss:.6f} |\n"
        )

        f.write("\n## Sign consistency\n\n")
        f.write("| Quantity | Value |\n")
        f.write("|---|---:|\n")
        f.write(f"| sign score | {sign_score}/{sign_max} |\n")
        f.write(f"| sign fraction | {sign_fraction:.6f} |\n")
        f.write(f"| heuristic random sign probability | {sign_pattern_probability_equiv_flip:.6f} |\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("Layered attribution strength:")
    print(f"early/radial RSS = {early_rss:.6f} sigma")
    print(f"late/transverse RSS = {late_rss:.6f} sigma")
    print(f"combined RSS = {total_rss:.6f} sigma")
    print(f"sign score = {sign_score}/{sign_max}")
    print(f"status = {status}")


if __name__ == "__main__":
    main()