"""Tests for scripts/validate_working_leo_production_receipt.py."""

from __future__ import annotations

import json
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "scripts"))

import build_working_leo_authorized_apply_runbook as runbook_builder  # noqa: E402
import validate_working_leo_production_receipt as validator  # noqa: E402


def write_json(path: Path, data: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def make_artifact(root: Path, relative: str, text: str = "ok\n") -> str:
    path = root / relative
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    return relative


def make_runbook(tmp_path: Path) -> Path:
    runbook = runbook_builder.build_runbook()
    path = tmp_path / "runbook.json"
    write_json(path, runbook)
    return path


def make_valid_receipt(tmp_path: Path, runbook_path: Path) -> Path:
    runbook = json.loads(runbook_path.read_text(encoding="utf-8"))
    score_path = make_artifact(
        tmp_path,
        "reports/direct-score.md",
        "Overall pass for scored coverage: `True`\nPrompts scored: `6/6`\n",
    )
    receipt = {
        "actual_after_apply_counts": runbook["expected_after_apply_counts"],
        "apply_output_paths": [make_artifact(tmp_path, "reports/apply.log")],
        "cleanup_readback": {
            "checks": {
                "cleanup_ok": True,
                "leftover_rehearsal_clone_or_staging_databases": [],
            }
        },
        "direct_claim_score_path": score_path,
        "explicit_authorization_record": {
            "authorized": True,
            "authorized_by": "operator",
            "scope": "integrated Working Leo packet set",
        },
        "expected_after_apply_counts": runbook["expected_after_apply_counts"],
        "git_commit_sha": "3351d2d",
        "known_residual_risks": ["GCP parity remains separate"],
        "operator_identity": "operator@example.com",
        "postflight_output_paths": [make_artifact(tmp_path, "reports/postflight.log")],
        "preflight_output_paths": [make_artifact(tmp_path, "reports/preflight.log")],
        "rollback_packet_paths": [make_artifact(tmp_path, "reports/rollback.sql")],
        "service_readback": {
            "ActiveState": "active",
            "MainPID": "1908033",
            "NRestarts": "0",
            "SubState": "running",
        },
        "telegram_or_handler_regression_paths": [make_artifact(tmp_path, "reports/handler.json", "{}\n")],
    }
    path = tmp_path / "receipt.json"
    write_json(path, receipt)
    return path


def test_valid_receipt_passes(tmp_path: Path):
    runbook_path = make_runbook(tmp_path)
    receipt_path = make_valid_receipt(tmp_path, runbook_path)

    result = validator.validate_receipt(receipt_path, runbook_path, repo_root=tmp_path)

    assert result["valid"] is True
    assert result["status"] == "valid"
    assert result["errors"] == []
    assert all(result["checks"].values())


def test_missing_receipt_fails(tmp_path: Path):
    runbook_path = make_runbook(tmp_path)

    result = validator.validate_receipt(tmp_path / "missing.json", runbook_path, repo_root=tmp_path)

    assert result["valid"] is False
    assert result["status"] == "missing_receipt"
    assert "receipt file does not exist" in result["errors"][0]


def test_receipt_rejects_missing_paths_and_bad_counts(tmp_path: Path):
    runbook_path = make_runbook(tmp_path)
    receipt_path = make_valid_receipt(tmp_path, runbook_path)
    receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
    receipt["actual_after_apply_counts"] = {"claims": 1}
    receipt["apply_output_paths"] = ["reports/missing.log"]
    write_json(receipt_path, receipt)

    result = validator.validate_receipt(receipt_path, runbook_path, repo_root=tmp_path)

    assert result["valid"] is False
    assert result["checks"]["actual_counts_match_expected"] is False
    assert result["checks"]["apply_output_paths_exist"] is False
    assert any("actual_after_apply_counts" in error for error in result["errors"])
    assert any("apply_output_paths" in error for error in result["errors"])


def test_receipt_rejects_failed_direct_claim_score(tmp_path: Path):
    runbook_path = make_runbook(tmp_path)
    receipt_path = make_valid_receipt(tmp_path, runbook_path)
    receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
    bad_score = make_artifact(tmp_path, "reports/direct-score.md", "Prompts scored: `3/6`\n")
    receipt["direct_claim_score_path"] = bad_score
    write_json(receipt_path, receipt)

    result = validator.validate_receipt(receipt_path, runbook_path, repo_root=tmp_path)

    assert result["valid"] is False
    assert result["checks"]["direct_claim_score_passes"] is False
