import json
import math
import os
from pathlib import Path

ROOT = Path(".")

INPUT_STRENGTH = ROOT / "results" / "row20_h0_attribution" / "row20_layered_attribution_strength.json"
INPUT_SIGN = ROOT / "results" / "row20_h0_attribution" / "row20_layered_sign_consistency.json"

OUTPUT_JSON = ROOT / "results" / "row20_h0_attribution" / "row20_coupled_bridge_test.json"
OUTPUT_REPORT = ROOT / "results" / "row20_h0_attribution" / "row20_coupled_bridge_test.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():
    strength = load(INPUT_STRENGTH)
    sign_data = load(INPUT_SIGN)

    residuals = sign_data["residuals"]

    # Current key residuals
    cmb = residuals["CMB_ell_A"]
    bao_h = residuals["BAO_H_z0_706"]
    bao_dm = residuals["BAO_D_M_z0_706"]
    sn = residuals["SN_pivot"]
    sh0es = residuals["SH0ES_overlay"]

    original = {
        "CMB_ell_A": cmb,
        "BAO_H": bao_h,
        "BAO_D_M": bao_dm,
        "SN_pivot": sn,
        "SH0ES": sh0es,
    }

    original_vec = list(original.values())
    original_rss = rss(original_vec)
    original_chi2 = chi2(original_vec)

    # Coupled bridge model:
    # One bridge amplitude b transfers stress between early/radial and late/transverse sides.
    #
    # Constraint:
    #   - Early/radial positive pulls are reduced by b.
    #   - Late/transverse negative pulls are increased toward zero by b.
    #   - No sign flip allowed.
    #
    # This is NOT a physics correction; it is a feasibility test:
    # Can any single coupled bridge amplitude reduce all major residuals coherently?
    best = None
    trials = []

    for i in range(0, 1001):
        b = i / 1000.0 * 6.0  # scan bridge strength 0 → 6 sigma-equivalent

        transformed = {
            "CMB_ell_A": cmb - b,
            "BAO_H": bao_h - b,
            "BAO_D_M": bao_dm + b,
            "SN_pivot": sn + b,
            "SH0ES": sh0es + b,
        }

        # no sign flip constraint:
        # CMB/BAO_H must remain >= 0, late/transverse must remain <= 0
        valid_no_flip = (
            transformed["CMB_ell_A"] >= 0
            and transformed["BAO_H"] >= 0
            and transformed["BAO_D_M"] <= 0
            and transformed["SN_pivot"] <= 0
            and transformed["SH0ES"] <= 0
        )

        transformed_vec = list(transformed.values())
        r = rss(transformed_vec)
        c = chi2(transformed_vec)

        item = {
            "bridge_strength": b,
            "rss": r,
            "chi2": c,
            "valid_no_flip": valid_no_flip,
            "transformed": transformed,
        }

        trials.append(item)

        if valid_no_flip:
            if best is None or r < best["rss"]:
                best = item

    if best is None:
        status = "no_valid_no_flip_bridge_found"
        improvement = 0.0
    else:
        improvement = original_rss - best["rss"]
        if improvement > 2.0:
            status = "coupled_bridge_feasible_strong"
        elif improvement > 1.0:
            status = "coupled_bridge_feasible_moderate"
        elif improvement > 0.25:
            status = "coupled_bridge_feasible_weak"
        else:
            status = "coupled_bridge_not_effective"

    interpretation = []

    interpretation.append(
        "This test asks whether a single coupled bridge amplitude can reduce early/radial and late/transverse residuals together without flipping the layered sign structure."
    )

    if best is not None:
        interpretation.append(
            f"Best no-flip bridge strength is {best['bridge_strength']:.3f} sigma-equivalent."
        )
        interpretation.append(
            f"Original RSS {original_rss:.3f} reduces to {best['rss']:.3f}, improvement {improvement:.3f}."
        )

    if status.startswith("coupled_bridge_feasible"):
        interpretation.append(
            "A coupled-layer bridge remains mathematically feasible under sign-preserving constraints."
        )
    else:
        interpretation.append(
            "A single coupled bridge amplitude does not sufficiently reduce the layered residuals; this route may be closed unless the bridge is non-linear or multi-component."
        )

    interpretation.append(
        "This is a feasibility diagnostic only. It does not modify physics, thresholds, datasets, parameters, or gate verdicts."
    )

    result = {
        "signature": "ROW20_COUPLED_BRIDGE_TEST_v1_NATIVE_DIAGNOSTIC",
        "context": "DIAGNOSTIC_NON_GATING",
        "original_residuals": original,
        "original_rss": original_rss,
        "original_chi2": original_chi2,
        "best_no_flip_bridge": best,
        "rss_improvement": improvement,
        "status": status,
        "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 Coupled Bridge Test\n\n")
        f.write("**Context:** DIAGNOSTIC_NON_GATING. No physics, thresholds, datasets, parameters, or gate verdicts changed.\n\n")

        f.write("## Original residual vector\n\n")
        f.write("| Node | Pull sigma |\n")
        f.write("|---|---:|\n")
        for k, v in original.items():
            f.write(f"| {k} | {v:.6f} |\n")

        f.write("\n## Coupled bridge result\n\n")
        f.write("| Quantity | Value |\n")
        f.write("|---|---:|\n")
        f.write(f"| original RSS | {original_rss:.6f} |\n")
        f.write(f"| original chi2 | {original_chi2:.6f} |\n")

        if best is not None:
            f.write(f"| best bridge strength | {best['bridge_strength']:.6f} |\n")
            f.write(f"| best RSS | {best['rss']:.6f} |\n")
            f.write(f"| best chi2 | {best['chi2']:.6f} |\n")
            f.write(f"| RSS improvement | {improvement:.6f} |\n")
        else:
            f.write("| best bridge strength | none |\n")
            f.write("| best RSS | none |\n")
            f.write("| RSS improvement | 0 |\n")

        f.write(f"| status | {status} |\n")

        if best is not None:
            f.write("\n## Best transformed residual vector\n\n")
            f.write("| Node | Pull sigma after bridge |\n")
            f.write("|---|---:|\n")
            for k, v in best["transformed"].items():
                f.write(f"| {k} | {v:.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("Coupled bridge test:")
    print(f"original RSS={original_rss:.6f}")
    if best is not None:
        print(f"best bridge strength={best['bridge_strength']:.6f}")
        print(f"best RSS={best['rss']:.6f}")
        print(f"RSS improvement={improvement:.6f}")
    print(f"status={status}")


if __name__ == "__main__":
    main()