"""Tests for scripts/assemble_working_leo_production_apply_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 assemble_working_leo_production_apply_receipt as assembler  # 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 test_current_assembly_refuses_without_authorization_or_session_logs():
    result = assembler.build_assembly()

    assert result["status"] == "not_ready_missing_or_unverified_session_evidence"
    assert result["receipt_ready"] is False
    assert result["production_apply_executed"] is False
    assert result["checks"]["authorization_verified"] is False
    assert result["checks"]["all_session_artifacts_exist"] is False
    assert result["assembled_receipt"] == {}
    assert "does not run SQL" in result["claim_ceiling"]


def test_assembly_emits_validator_ready_receipt_from_fixture(tmp_path: Path):
    expected_counts = {"claims": 1, "sources": 2}
    runbook = {
        "expected_after_apply_counts": expected_counts,
        "production_apply_receipt_required_fields": [
            "explicit_authorization_record",
            "operator_identity",
            "git_commit_sha",
            "preflight_output_paths",
            "apply_output_paths",
            "postflight_output_paths",
            "expected_after_apply_counts",
            "actual_after_apply_counts",
            "telegram_or_handler_regression_paths",
            "direct_claim_score_path",
            "service_readback",
            "cleanup_readback",
            "rollback_packet_paths",
            "known_residual_risks",
        ],
    }
    session_plan = {
        "production_apply_executed": False,
        "receipt_field_sources_after_execution": {
            "preflight_output_paths": ["logs/preflight.log"],
            "apply_output_paths": ["logs/apply.log"],
            "postflight_output_paths": ["logs/postflight.log"],
            "telegram_or_handler_regression_paths": ["logs/handler.log"],
            "service_readback": "logs/service.log",
            "cleanup_readback": "logs/cleanup.log",
            "rollback_packet_paths": ["logs/rollback.sql"],
        },
    }
    template = {
        "production_apply_executed": False,
        "valid_production_receipt": False,
        "receipt_template": {
            "direct_claim_score_path": "logs/direct-score.md",
            "known_residual_risks": ["GCP parity remains separate"],
        },
    }
    auth = {
        "safe_to_enter_apply_window": True,
        "production_apply_executed": False,
        "operator_identity": "operator@example.com",
        "deployed_sha": "db0c538",
        "expected_authorization_text": "authorized",
    }
    for relative in (
        "logs/preflight.log",
        "logs/apply.log",
        "logs/postflight.log",
        "logs/handler.log",
        "logs/rollback.sql",
    ):
        (tmp_path / relative).parent.mkdir(parents=True, exist_ok=True)
        (tmp_path / relative).write_text("ok\n", encoding="utf-8")
    (tmp_path / "logs/direct-score.md").write_text(
        "Overall pass for scored coverage: `True`\nPrompts scored: `6/6`\n",
        encoding="utf-8",
    )
    (tmp_path / "logs/service.log").write_text(
        "ActiveState=active\nSubState=running\nMainPID=1908033\nNRestarts=0\n",
        encoding="utf-8",
    )
    (tmp_path / "logs/cleanup.log").write_text("", encoding="utf-8")
    write_json(tmp_path / "runbook.json", runbook)
    write_json(tmp_path / "session.json", session_plan)
    write_json(tmp_path / "template.json", template)
    write_json(tmp_path / "auth.json", auth)
    write_json(tmp_path / "counts.json", expected_counts)

    result = assembler.build_assembly(
        runbook_path=tmp_path / "runbook.json",
        session_plan_path=tmp_path / "session.json",
        receipt_template_path=tmp_path / "template.json",
        auth_verification_path=tmp_path / "auth.json",
        actual_counts_path=tmp_path / "counts.json",
        receipt_out=tmp_path / "receipt.json",
        repo_root=tmp_path,
    )
    write_json(tmp_path / "receipt.json", result["assembled_receipt"])
    validation = validator.validate_receipt(
        tmp_path / "receipt.json",
        tmp_path / "runbook.json",
        repo_root=tmp_path,
    )

    assert result["receipt_ready"] is True
    assert result["checks"]["actual_counts_match_expected"] is True
    assert validation["valid"] is True
