import json
import math
import os
from pathlib import Path

ROOT = Path(".")

INPUT_ANCHORED = ROOT / "results" / "row20_h0_attribution" / "row20_BAO_DM_anchored_bridge.json"

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


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


def rss(vals):
    return math.sqrt(sum(v * v for v in vals))


def chi2(vals):
    return sum(v * v for v in vals)


def main():
    data = load(INPUT_ANCHORED)

    original = data["original_residuals"]
    transformed = data["transformed_residuals"]

    early_keys = ["CMB_ell_A", "BAO_H"]
    late_keys = ["BAO_D_M", "SN_pivot", "SH0ES"]

    original_early = [original[k] for k in early_keys]
    transformed_early = [transformed[k] for k in early_keys]

    original_late = [original[k] for k in late_keys]
    transformed_late = [transformed[k] for k in late_keys]

    original_early_rss = rss(original_early)
    transformed_early_rss = rss(transformed_early)
    early_improvement = original_early_rss - transformed_early_rss

    original_late_rss = rss(original_late)
    transformed_late_rss = rss(transformed_late)
    late_improvement = original_late_rss - transformed_late_rss

    total_improvement = data["rss_improvement"]

    neutralized_BAO_DM = abs(transformed["BAO_D_M"]) < 1e-9
    sign_preserved = data["no_forbidden_flip"]

    # Balance metric:
    # ratio close to 1 means both early and late sides improved comparably.
    if max(abs(early_improvement), abs(late_improvement)) == 0:
        balance_ratio = 0
    else:
        balance_ratio = min(abs(early_improvement), abs(late_improvement)) / max(
            abs(early_improvement), abs(late_improvement)
        )

    ownership_tests = {
        "BAO_DM_bridge_neutralized": neutralized_BAO_DM,
        "layered_sign_structure_preserved": sign_preserved,
        "early_side_improves": early_improvement > 0,
        "late_side_improves": late_improvement > 0,
        "balanced_transfer_ratio_ge_0_25": balance_ratio >= 0.25,
        "total_RSS_improvement_ge_2sigma": total_improvement >= 2.0,
    }

    score = sum(1 for v in ownership_tests.values() if v)
    max_score = len(ownership_tests)

    if score == max_score:
        status = "bridge_theory_ownership_strong_candidate"
    elif score >= 4:
        status = "bridge_theory_ownership_partial_candidate"
    else:
        status = "bridge_theory_ownership_weak"

    interpretation = []

    interpretation.append(
        "This test asks whether the BAO-D_M anchored bridge behaves like a lawful UTFANSWF layered transfer rather than an arbitrary correction."
    )

    if neutralized_BAO_DM:
        interpretation.append(
            "The bridge exactly neutralizes the transverse BAO D_M node, consistent with a geometry-anchored transfer."
        )

    if sign_preserved:
        interpretation.append(
            "The bridge preserves the layered sign structure, so it does not erase the observed early/late split by force."
        )

    if early_improvement > 0 and late_improvement > 0:
        interpretation.append(
            "Both early/radial and late/transverse RSS improve, supporting coupled-layer behavior."
        )

    if balance_ratio >= 0.25:
        interpretation.append(
            "The transfer is not one-sided; both layer groups receive nontrivial improvement."
        )
    else:
        interpretation.append(
            "The transfer is highly one-sided; theory ownership remains weak."
        )

    interpretation.append(
        "This remains diagnostic. To become a solution, the bridge must be derived from an explicit UTFANSWF operator or mapping equation."
    )

    result = {
        "signature": "ROW20_BRIDGE_THEORY_OWNERSHIP_v1_NATIVE_DIAGNOSTIC",
        "context": "DIAGNOSTIC_NON_GATING",
        "bridge_strength": data["bridge_strength"],
        "bridge_strength_source": data["bridge_strength_source"],
        "group_metrics": {
            "early_radial": {
                "nodes": early_keys,
                "original_rss": original_early_rss,
                "transformed_rss": transformed_early_rss,
                "improvement": early_improvement,
            },
            "late_transverse": {
                "nodes": late_keys,
                "original_rss": original_late_rss,
                "transformed_rss": transformed_late_rss,
                "improvement": late_improvement,
            },
            "balance_ratio": balance_ratio,
            "total_rss_improvement": total_improvement,
        },
        "ownership_tests": ownership_tests,
        "score": score,
        "max_score": max_score,
        "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 — Bridge Theory Ownership Diagnostic\n\n")
        f.write("**Context:** DIAGNOSTIC_NON_GATING. No physics, thresholds, datasets, parameters, or gate verdicts changed.\n\n")

        f.write("## Bridge\n\n")
        f.write("| Quantity | Value |\n")
        f.write("|---|---:|\n")
        f.write(f"| bridge strength | {data['bridge_strength']:.6f} |\n")
        f.write(f"| source | {data['bridge_strength_source']} |\n\n")

        f.write("## Group metrics\n\n")
        f.write("| Group | Original RSS | Transformed RSS | Improvement |\n")
        f.write("|---|---:|---:|---:|\n")
        f.write(
            f"| early/radial | {original_early_rss:.6f} | "
            f"{transformed_early_rss:.6f} | {early_improvement:.6f} |\n"
        )
        f.write(
            f"| late/transverse | {original_late_rss:.6f} | "
            f"{transformed_late_rss:.6f} | {late_improvement:.6f} |\n"
        )
        f.write(f"| balance ratio | | | {balance_ratio:.6f} |\n")
        f.write(f"| total RSS improvement | | | {total_improvement:.6f} |\n\n")

        f.write("## Ownership tests\n\n")
        f.write("| Test | Pass |\n")
        f.write("|---|---:|\n")
        for k, v in ownership_tests.items():
            f.write(f"| {k} | {v} |\n")

        f.write(f"\nScore: **{score}/{max_score}**\n\n")

        f.write("## 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("Bridge theory ownership:")
    print(f"score={score}/{max_score}")
    print(f"early improvement={early_improvement:.6f}")
    print(f"late improvement={late_improvement:.6f}")
    print(f"balance ratio={balance_ratio:.6f}")
    print(f"status={status}")


if __name__ == "__main__":
    main()