from __future__ import annotations

import json

import pytest

from src.services.backup_dr_readiness_matrix import load_latest_backup_dr_readiness_matrix


def test_load_latest_backup_dr_readiness_matrix_reads_newest_file(tmp_path):
    older = _snapshot(generated_at="2026-06-03T00:00:00+08:00", completion=88)
    newer = _snapshot(generated_at="2026-06-04T00:00:00+08:00", completion=91)
    (tmp_path / "backup_dr_readiness_matrix_2026-06-03.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "backup_dr_readiness_matrix_2026-06-04.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_backup_dr_readiness_matrix(tmp_path)

    assert loaded["generated_at"] == "2026-06-04T00:00:00+08:00"
    assert loaded["program_status"]["overall_completion_percent"] == 91
    assert loaded["rollups"]["total_rows"] == 3
    assert loaded["operation_boundaries"]["restore_execution_allowed"] is False


def test_backup_dr_readiness_matrix_requires_read_only_mode(tmp_path):
    snapshot = _snapshot()
    snapshot["program_status"]["read_only_mode"] = False
    (tmp_path / "backup_dr_readiness_matrix_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="read_only_mode"):
        load_latest_backup_dr_readiness_matrix(tmp_path)


def test_backup_dr_readiness_matrix_requires_blocked_operations(tmp_path):
    snapshot = _snapshot()
    snapshot["operation_boundaries"]["credential_marker_write_allowed"] = True
    (tmp_path / "backup_dr_readiness_matrix_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="operation boundaries"):
        load_latest_backup_dr_readiness_matrix(tmp_path)


def test_backup_dr_readiness_matrix_requires_total_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["total_rows"] = 999
    (tmp_path / "backup_dr_readiness_matrix_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="total_rows"):
        load_latest_backup_dr_readiness_matrix(tmp_path)


def test_backup_dr_readiness_matrix_requires_action_required_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["action_required_row_ids"] = []
    (tmp_path / "backup_dr_readiness_matrix_2026-06-04.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="action_required_row_ids"):
        load_latest_backup_dr_readiness_matrix(tmp_path)


def test_backup_dr_readiness_matrix_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_backup_dr_readiness_matrix(tmp_path)


def _snapshot(
    *,
    generated_at: str = "2026-06-04T00:00:00+08:00",
    completion: int = 91,
) -> dict:
    return {
        "schema_version": "backup_dr_readiness_matrix_v1",
        "generated_at": generated_at,
        "source_target_inventory_ref": "docs/evaluations/backup_dr_target_inventory_2026-06-04.json",
        "source_refs": ["docs/runbooks/BACKUP-STATUS.md"],
        "program_status": {
            "overall_completion_percent": completion,
            "current_priority": "P1",
            "current_task_id": "P1-102",
            "next_task_id": "P1-201",
            "read_only_mode": True,
        },
        "rollups": {
            "total_rows": 3,
            "by_overall_readiness": {"ready": 1, "action_required": 1, "blocked": 1},
            "by_restore_drill_status": {"approval_required": 2, "blocked": 1},
            "by_offsite_status": {"verified": 2, "blocked": 1},
            "blocked_row_ids": ["credential_escrow_markers"],
            "action_required_row_ids": ["signoz"],
        },
        "readiness_rows": [
            _row("gitea", "ready", "verified"),
            _row("signoz", "action_required", "verified"),
            _row("credential_escrow_markers", "blocked", "blocked"),
        ],
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "backup_execution_allowed": False,
            "restore_execution_allowed": False,
            "offsite_sync_execution_allowed": False,
            "credential_marker_write_allowed": False,
            "schedule_change_allowed": False,
            "destructive_prune_allowed": False,
        },
        "approval_boundaries": {
            "sdk_installation_allowed": False,
            "paid_api_call_allowed": False,
            "shadow_or_canary_allowed": False,
            "production_routing_allowed": False,
            "destructive_operation_allowed": False,
        },
    }


def _row(target_id: str, readiness: str, offsite: str) -> dict:
    return {
        "target_id": target_id,
        "display_name": target_id,
        "overall_readiness": readiness,
        "freshness_status": "verified" if readiness != "blocked" else "blocked",
        "integrity_status": "verified" if readiness != "blocked" else "not_applicable",
        "restore_drill_status": "blocked" if readiness == "blocked" else "approval_required",
        "offsite_status": offsite,
        "notification_policy": "failure-only",
        "gate_status": "credential_approval_required" if readiness == "blocked" else "restore_approval_required",
        "evidence_level": "blocked_live_evidence" if readiness == "blocked" else "runbook_live_refresh",
        "evidence_refs": ["docs/runbooks/BACKUP-STATUS.md"],
        "blocker_summary": "none" if readiness != "blocked" else "blocked",
        "next_action": "next",
    }
