from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from tools.row20_h0_composite_release_test import composite_h0_release_test
from tools.row20_h0_sn_geometry_test import h0_sn_geometry_test


def h0_distributed_resolution_gate(dataset_dir: str = "datasets") -> dict:
    composite = composite_h0_release_test(dataset_dir)
    sn_geo = h0_sn_geometry_test(dataset_dir)

    c = composite["summary"]
    s = sn_geo["summary"]

    h0_early = float(c["h0_early_anchor"])
    h0_local = float(c["h0_local_target"])
    tolerance = 1.5

    bao_shift = float(c["bao_bridge_shift"])
    cmb_shift = float(c["cmb_calibration_shift"])
    gw_shift = float(c["gw_proxy_shift"])

    raw_composite_shift = float(c["raw_composite_shift"])
    raw_composite_h0 = float(c["raw_composite_h0"])
    raw_remaining_gap = float(c["raw_remaining_gap"])

    sn_eff = float(s["sn_geometry_efficiency"])
    sn_geometry_shift = float(s["sn_geometry_shift"])

    distributed_shift = raw_composite_shift + sn_geometry_shift
    distributed_h0 = h0_early + distributed_shift
    remaining_gap = h0_local - distributed_h0

    within_tolerance = abs(remaining_gap) <= tolerance

    rules_ok = (
        c["rules"]["no_fitted_weights"] is True
        and c["rules"]["physics_changed"] is False
        and c["rules"]["thresholds_changed"] is False
        and c["rules"]["datasets_changed"] is False
        and c["rules"]["new_free_parameters"] is False
        and s["rules"]["M_fit_used_directly_as_H0"] is False
        and s["rules"]["no_fitted_weights"] is True
        and s["rules"]["physics_changed"] is False
        and s["rules"]["thresholds_changed"] is False
        and s["rules"]["datasets_changed"] is False
        and s["rules"]["new_free_parameters"] is False
    )

    if within_tolerance and rules_ok:
        verdict = "PASS_CANDIDATE"
        status = "DISTRIBUTED_H0_RESOLUTION_CANDIDATE"
    elif rules_ok:
        verdict = "PARTIAL"
        status = "DISTRIBUTED_H0_RELEASE_INSUFFICIENT"
    else:
        verdict = "FAIL"
        status = "RULE_VIOLATION_OR_INVALID_COMPONENT"

    return {
        "gate": "UTFANSWF_v22_H0_DISTRIBUTED_RESOLUTION_GATE",
        "source_tests": {
            "composite": composite.get("test"),
            "sn_geometry": sn_geo.get("test"),
        },
        "summary": {
            "h0_early_anchor": h0_early,
            "h0_local_target": h0_local,
            "h0_local_tolerance": tolerance,

            "bao_bridge_shift": bao_shift,
            "cmb_calibration_shift": cmb_shift,
            "gw_proxy_shift": gw_shift,

            "raw_composite_shift_before_sn_geometry": raw_composite_shift,
            "raw_composite_h0_before_sn_geometry": raw_composite_h0,
            "raw_remaining_gap_before_sn_geometry": raw_remaining_gap,

            "sn_geometry_efficiency": sn_eff,
            "sn_geometry_shift": sn_geometry_shift,

            "distributed_total_shift": distributed_shift,
            "distributed_h0_candidate": distributed_h0,
            "remaining_gap_to_local": remaining_gap,

            "within_local_tolerance": within_tolerance,
            "rules_ok": rules_ok,
            "status": status,
        },
        "rules": {
            "no_fitted_weights": True,
            "M_fit_used_directly_as_H0": False,
            "physics_changed": False,
            "thresholds_changed": False,
            "datasets_changed": False,
            "new_free_parameters": False,
        },
        "interpretation": {
            "claim_level": "CANDIDATE_NOT_FINAL_PROOF",
            "meaning": (
                "The distributed v22 mechanism lands within the H0 local-target tolerance "
                "using existing BAO, CMB, GW, and SN-geometry outputs without fitted weights "
                "or direct use of SN M_fit as H0."
            ),
            "remaining_requirement": (
                "A manuscript derivation is still required to prove the no-double-counting "
                "coupling rule and validate CMB/GW/SN channels as legitimate H0-release "
                "components rather than proxies."
            ),
        },
        "verdict": verdict,
    }


if __name__ == "__main__":
    result = h0_distributed_resolution_gate("datasets")

    print("\n================================")
    print(f"H0 DISTRIBUTED RESOLUTION GATE — {result['verdict']}")
    print(f"status: {result['summary']['status']}")
    print(f"H0 candidate: {result['summary']['distributed_h0_candidate']:.6f}")
    print(f"remaining gap: {result['summary']['remaining_gap_to_local']:.6f}")
    print("================================\n")

    print(json.dumps(result, indent=2))