from __future__ import annotations

import json

import pytest

from src.services.ai_agent_host_stateful_version_inventory import (
    load_latest_ai_agent_host_stateful_version_inventory,
)


def test_load_latest_ai_agent_host_stateful_version_inventory_reads_committed_snapshot():
    data = load_latest_ai_agent_host_stateful_version_inventory()

    assert data["schema_version"] == "ai_agent_host_stateful_version_inventory_v1"
    assert data["program_status"]["overall_completion_percent"] == 86
    assert data["program_status"]["current_task_id"] == "P2-402F"
    assert data["program_status"]["next_task_id"] == "P2-402G"
    assert data["program_status"]["read_only_mode"] is True
    assert data["program_status"]["runtime_authority"] == (
        "host_stateful_readonly_inventory_no_upgrade_or_restart"
    )
    assert data["operation_boundaries"]["read_only_inventory_allowed"] is True
    assert data["operation_boundaries"]["ssh_login_allowed"] is False
    assert data["operation_boundaries"]["kubectl_command_execution_allowed"] is False
    assert data["operation_boundaries"]["apt_upgrade_allowed"] is False
    assert data["operation_boundaries"]["k3s_upgrade_allowed"] is False
    assert data["operation_boundaries"]["node_drain_allowed"] is False
    assert data["operation_boundaries"]["reboot_allowed"] is False
    assert data["operation_boundaries"]["stateful_service_restart_allowed"] is False
    assert data["operation_boundaries"]["telegram_direct_send_allowed"] is False
    assert data["operation_boundaries"]["conversation_transcript_allowed"] is False
    assert data["rollups"]["host_count"] == len(data["host_inventory"]) == 5
    assert data["rollups"]["k3s_node_count"] == len(data["k3s_inventory"]["nodes"]) == 2
    assert data["rollups"]["stateful_service_count"] == len(data["stateful_services"]) == 12
    assert data["rollups"]["readonly_probe_step_count"] == len(data["readonly_probe_plan"]) == 6
    assert data["rollups"]["ssh_login_allowed_count"] == 0
    assert data["rollups"]["kubectl_command_execution_allowed_count"] == 0
    assert data["rollups"]["apt_upgrade_allowed_count"] == 0
    assert data["rollups"]["k3s_upgrade_allowed_count"] == 0
    assert data["rollups"]["node_drain_allowed_count"] == 0
    assert data["rollups"]["reboot_allowed_count"] == 0
    assert data["rollups"]["stateful_service_restart_allowed_count"] == 0
    assert data["rollups"]["telegram_direct_send_allowed_count"] == 0
    assert data["rollups"]["conversation_transcript_allowed_count"] == 0
    assert all(host["readonly_only"] is True for host in data["host_inventory"])
    assert all(service["restart_authorized"] is False for service in data["stateful_services"])


def test_ai_agent_host_stateful_version_inventory_blocks_ssh(tmp_path):
    snapshot = _snapshot()
    snapshot["operation_boundaries"]["ssh_login_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

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


def test_ai_agent_host_stateful_version_inventory_rejects_rollup_mismatch(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["host_count"] = 99
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="rollup counts"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def test_ai_agent_host_stateful_version_inventory_rejects_host_reboot(tmp_path):
    snapshot = _snapshot()
    snapshot["host_inventory"][0]["reboot_authorized"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="host inventory"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def test_ai_agent_host_stateful_version_inventory_rejects_k3s_drain(tmp_path):
    snapshot = _snapshot()
    snapshot["k3s_inventory"]["nodes"][0]["drain_authorized"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="K3s nodes"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def test_ai_agent_host_stateful_version_inventory_rejects_stateful_restart(tmp_path):
    snapshot = _snapshot()
    snapshot["stateful_services"][0]["restart_authorized"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="stateful services"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def test_ai_agent_host_stateful_version_inventory_requires_maintenance_fields(tmp_path):
    snapshot = _snapshot()
    snapshot["maintenance_window_approval_package"]["required_fields"] = ["owner"]
    snapshot["rollups"]["maintenance_required_field_count"] = 1
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="maintenance window approval package"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def test_ai_agent_host_stateful_version_inventory_rejects_transcript_markers(tmp_path):
    snapshot = _snapshot()
    snapshot["program_status"]["status_note"] = "禁止放入 My request for Codex"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden work-window conversation content"):
        load_latest_ai_agent_host_stateful_version_inventory(tmp_path)


def _write_snapshot(tmp_path, snapshot: dict) -> None:
    (tmp_path / "ai_agent_host_stateful_version_inventory_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )


def _snapshot() -> dict:
    return json.loads(json.dumps(load_latest_ai_agent_host_stateful_version_inventory()))
