from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]


def _run(script: str) -> None:
    subprocess.run(
        [sys.executable, script],
        cwd=ROOT,
        check=True,
        capture_output=True,
        text=True,
        encoding="utf-8",
    )


def test_build_calibration_priority_and_change_ledger(tmp_path):
    _run("tools/build_calibration_priority_v1.py")
    _run("tools/build_calibration_change_ledger_v4.py")
    _run("tools/validate_calibration_change_ledger_v1.py")

    priority_path = ROOT / "Temp" / "calibration_priority_v1.json"
    ledger_path = ROOT / "Temp" / "calibration_change_ledger_v4.json"

    priority = json.loads(priority_path.read_text(encoding="utf-8"))
    ledger = json.loads(ledger_path.read_text(encoding="utf-8"))

    assert priority["status"] == "CALIBRATION_PRIORITY_OK"
    assert priority["priority_count"] >= 5
    assert priority["priority_list"]
    assert priority["priority_basis"] in {"alpha_feedback_loop_v2", "registry_warning_fallback"}

    assert ledger["formula_id"] == "CALIBRATION_CHANGE_LEDGER_V4"
    assert ledger["threshold_change_without_ledger_count"] == 0
    assert len(ledger["changes"]) >= 5


def test_calibration_backlog_workflow_and_script_exist():
    workflow = ROOT / ".gitea" / "workflows" / "calibration_backlog.yml"
    package = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))
    # assert workflow.exists()  # Cleaned up in workflows consolidation
    assert "ops:calibration-backlog" in package["scripts"]
    assert "ops:calibration-review-report" in package["scripts"]
    assert "ops:calibration-approval-list" in package["scripts"]
    assert "ops:calibration-decision-draft" in package["scripts"]


def test_build_calibration_review_report(tmp_path):
    _run("tools/build_calibration_priority_v1.py")
    _run("tools/build_calibration_change_ledger_v4.py")
    _run("tools/build_calibration_review_report_v1.py")

    report_json = ROOT / "Temp" / "calibration_review_report_v1.json"
    report_md = ROOT / "Temp" / "calibration_review_report_v1.md"
    payload = json.loads(report_json.read_text(encoding="utf-8"))
    text = report_md.read_text(encoding="utf-8")

    assert payload["formula_id"] == "CALIBRATION_REVIEW_REPORT_V1"
    assert payload["summary"]["total_thresholds"] >= 1
    assert payload["top_priority_rows"]
    assert "Calibration Review Report" in text
    assert "Review Candidates" in text


def test_build_calibration_approval_list(tmp_path):
    _run("tools/build_calibration_priority_v1.py")
    _run("tools/build_calibration_change_ledger_v4.py")
    _run("tools/build_calibration_review_report_v1.py")
    _run("tools/build_calibration_approval_list_v1.py")

    approval_json = ROOT / "Temp" / "calibration_approval_list_v1.json"
    approval_md = ROOT / "Temp" / "calibration_approval_list_v1.md"
    payload = json.loads(approval_json.read_text(encoding="utf-8"))
    text = approval_md.read_text(encoding="utf-8")

    assert payload["formula_id"] == "CALIBRATION_APPROVAL_LIST_V1"
    assert payload["approval_candidate_count"] >= 1
    assert payload["approval_candidates"]
    assert "Calibration Approval List" in text
    assert "Approval Candidates" in text


def test_build_calibration_decision_draft(tmp_path):
    _run("tools/build_calibration_priority_v1.py")
    _run("tools/build_calibration_change_ledger_v4.py")
    _run("tools/build_calibration_review_report_v1.py")
    _run("tools/build_calibration_approval_list_v1.py")
    _run("tools/build_calibration_decision_draft_v1.py")

    decision_json = ROOT / "Temp" / "calibration_decision_draft_v1.json"
    decision_md = ROOT / "Temp" / "calibration_decision_draft_v1.md"
    payload = json.loads(decision_json.read_text(encoding="utf-8"))
    text = decision_md.read_text(encoding="utf-8")

    assert payload["formula_id"] == "CALIBRATION_DECISION_DRAFT_V1"
    assert payload["decision_count"] >= 1
    assert payload["summary"]["APPROVE"] >= 1
    assert payload["summary"]["HOLD"] >= 1
    assert payload["summary"]["REJECT"] >= 0
    assert "Calibration Decision Draft" in text
    assert "Decision Table" in text


if __name__ == "__main__":
    print("[START] Running Calibration Priority Tests directly...")
    
    # Mock tmp_path
    class TmpPathMock:
        def __init__(self, p):
            self.p = Path(p)
        def __truediv__(self, other):
            return self.p / other
    
    tmp = TmpPathMock("Temp")
    
    print("1/5 Running test_build_calibration_priority_and_change_ledger...")
    test_build_calibration_priority_and_change_ledger(tmp)
    
    print("2/5 Running test_calibration_backlog_workflow_and_script_exist...")
    test_calibration_backlog_workflow_and_script_exist()
    
    print("3/5 Running test_build_calibration_review_report...")
    test_build_calibration_review_report(tmp)
    
    print("4/5 Running test_build_calibration_approval_list...")
    test_build_calibration_approval_list(tmp)
    
    print("5/5 Running test_build_calibration_decision_draft...")
    test_build_calibration_decision_draft(tmp)
    
    print("[SUCCESS] ALL TESTS PASSED SUCCESSFULLY! (CALIBRATION_PRIORITY_OK)")
