import json
import math
import os
from pathlib import Path

ROOT = Path(".")

INPUT_SIGN = ROOT / "results" / "row20_h0_attribution" / "row20_layered_sign_consistency.json"
INPUT_ORIGIN = ROOT / "results" / "row20_h0_attribution" / "row20_bridge_origin_probe.json"

OUTPUT_JSON = ROOT / "results" / "row20_h0_attribution" / "row20_BAO_DM_anchored_bridge.json"
OUTPUT_REPORT = ROOT / "results" / "row20_h0_attribution" / "row20_BAO_DM_anchored_bridge.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 sign(x):
    if x > 0:
        return "+"
    if x < 0:
        return "-"
    return "0"


def main():
    sign_data = load(INPUT_SIGN)
    origin = load(INPUT_ORIGIN)

    residuals = sign_data["residuals"]

    original = {
        "CMB_ell_A": residuals["CMB_ell_A"],
        "BAO_H": residuals["BAO_H_z0_706"],
        "BAO_D_M": residuals["BAO_D_M_z0_706"],
        "SN_pivot": residuals["SN_pivot"],
        "SH0ES": residuals["SH0ES_overlay"],
    }

    # Anchor bridge strength to BAO D_M pull magnitude.
    bridge_strength = abs(original["BAO_D_M"])

    transformed = {
        "CMB_ell_A": original["CMB_ell_A"] - bridge_strength,
        "BAO_H": original["BAO_H"] - bridge_strength,
        "BAO_D_M": original["BAO_D_M"] + bridge_strength,
        "SN_pivot": original["SN_pivot"] + bridge_strength,
        "SH0ES": original["SH0ES"] + bridge_strength,
    }

    original_rss = rss(original.values())
    transformed_rss = rss(transformed.values())
    rss_improvement = original_rss - transformed_rss

    original_signs = {k: sign(v) for k, v in original.items()}
    transformed_signs = {k: sign(v) for k, v in transformed.items()}

    no_forbidden_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
    )

    interpretation = []

    interpretation.append(
        "This test applies a diagnostic coupled bridge anchored exactly to the BAO D_M residual magnitude."
    )

    if no_forbidden_flip:
        interpretation.append(
            "The BAO-D_M anchored bridge preserves the expected layered sign structure and neutralizes the transverse BAO bridge node."
        )
    else:
        interpretation.append(
            "The BAO-D_M anchored bridge causes a forbidden sign flip or does not neutralize the intended bridge node."
        )

    if rss_improvement > 2:
        interpretation.append(
            "The bridge produces a strong RSS reduction without introducing a free fitted bridge strength."
        )
        status = "BAO_DM_anchored_bridge_strong"
    elif rss_improvement > 1:
        interpretation.append(
            "The bridge produces a moderate RSS reduction."
        )
        status = "BAO_DM_anchored_bridge_moderate"
    else:
        interpretation.append(
            "The bridge does not sufficiently reduce the layered residual vector."
        )
        status = "BAO_DM_anchored_bridge_weak"

    result = {
        "signature": "ROW20_BAO_DM_ANCHORED_BRIDGE_v1_NATIVE_DIAGNOSTIC",
        "context": "DIAGNOSTIC_NON_GATING",
        "bridge_strength_source": "abs(BAO_D_M_z0_706_pull)",
        "bridge_strength": bridge_strength,
        "original_residuals": original,
        "transformed_residuals": transformed,
        "original_rss": original_rss,
        "transformed_rss": transformed_rss,
        "rss_improvement": rss_improvement,
        "original_signs": original_signs,
        "transformed_signs": transformed_signs,
        "no_forbidden_flip": no_forbidden_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 — BAO D_M Anchored Bridge 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 source | abs(BAO D_M z=0.706 pull) |\n")
        f.write(f"| bridge strength | {bridge_strength:.6f} |\n\n")

        f.write("## Residual transformation\n\n")
        f.write("| Node | Original pull σ | Transformed pull σ | Original sign | Transformed sign |\n")
        f.write("|---|---:|---:|---:|---:|\n")
        for k in original:
            f.write(
                f"| {k} | {original[k]:.6f} | {transformed[k]:.6f} | "
                f"{original_signs[k]} | {transformed_signs[k]} |\n"
            )

        f.write("\n## RSS\n\n")
        f.write("| Quantity | Value |\n")
        f.write("|---|---:|\n")
        f.write(f"| original RSS | {original_rss:.6f} |\n")
        f.write(f"| transformed RSS | {transformed_rss:.6f} |\n")
        f.write(f"| RSS improvement | {rss_improvement:.6f} |\n")
        f.write(f"| no forbidden flip | {no_forbidden_flip} |\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("BAO D_M anchored bridge:")
    print(f"bridge strength={bridge_strength:.6f}")
    print(f"original RSS={original_rss:.6f}")
    print(f"transformed RSS={transformed_rss:.6f}")
    print(f"RSS improvement={rss_improvement:.6f}")
    print(f"no forbidden flip={no_forbidden_flip}")
    print(f"verdict={status}")


if __name__ == "__main__":
    main()