from __future__ import annotations

import copy
import json

import pytest

from src.services.awoooi_status_cleanup_dashboard import (
    load_latest_awoooi_status_cleanup_dashboard,
)


def test_load_latest_awoooi_status_cleanup_dashboard_reads_committed_snapshot():
    data = load_latest_awoooi_status_cleanup_dashboard()

    assert data["schema_version"] == "awoooi_status_cleanup_dashboard_v1"
    assert data["summary"]["dashboard_status"] == "controlled_status_cleanup_package_ready"
    assert data["summary"]["gate_count"] == 5
    assert data["summary"]["blocked_gate_count"] == 0
    assert data["summary"]["accepted_owner_flag_count"] == data["summary"]["required_owner_flag_count"]
    assert data["summary"]["required_owner_flag_count"] >= 1
    assert data["summary"]["approved_update_section_count"] == data["summary"]["required_update_section_count"]
    assert data["summary"]["required_update_section_count"] >= 1
    assert data["summary"]["approved_target_path_count"] == data["summary"]["target_path_count"]
    assert data["summary"]["target_path_count"] >= 1
    assert data["summary"]["boundary_ack_count"] == data["summary"]["required_boundary_ack_count"]
    assert data["summary"]["required_boundary_ack_count"] >= 1
    assert data["summary"]["controlled_status_cleanup_package_ready"] is True
    assert data["summary"]["controlled_owner_acknowledgements_ready"] is True
    assert data["summary"]["controlled_dry_run_package_ready"] is True
    assert data["summary"]["controlled_post_apply_verifier_required"] is True
    assert data["summary"]["apply_allowed"] is False
    assert data["summary"]["memory_write_authorized"] is False
    assert data["summary"]["wazuh_api_live_query_authorized"] is False
    assert data["summary"]["runtime_execution_authorized"] is False
    assert data["summary"]["wazuh_handoff_status"] == "blocked_not_released"
    assert data["summary"]["wazuh_handoff_base_commit"] == "b540fc0c"
    assert data["summary"]["wazuh_handoff_commit_count"] == 7
    assert data["summary"]["wazuh_handoff_patch_count"] == 7
    assert data["summary"]["wazuh_live_metadata_owner_count"] == 0
    assert data["summary"]["wazuh_secret_metadata_count"] == 0
    assert data["summary"]["wazuh_live_agent_registry_readback"] == 0
    assert data["summary"]["iwooos_wazuh_runtime_gate"] == 0
    assert data["summary"]["wazuh_active_response_count"] == 0
    assert data["summary"]["wazuh_agent_visibility_status"] == "blocked_waiting_manager_agent_registry_readback"
    assert data["summary"]["wazuh_manager_agent_registry_readback_passed"] is False
    assert data["summary"]["wazuh_iwooos_live_route_readback_passed"] is False
    assert data["summary"]["wazuh_dashboard_agent_list_recovered"] is False
    assert data["summary"]["wazuh_agent_visibility_runtime_gate_count"] == 0
    assert data["summary"]["wazuh_runtime_gate_count"] == 0
    assert data["memory_write_authorized"] is False
    assert data["runtime_execution_authorized"] is False
    assert data["wazuh_handoff"]["wazuh_api_live_query_authorized"] is False
    assert data["wazuh_handoff"]["base_commit"] == "b540fc0c"
    assert data["wazuh_handoff"]["patch_count"] == 7
    assert data["wazuh_handoff"]["live_metadata_owner_count"] == 0
    assert data["wazuh_handoff"]["wazuh_live_agent_registry_readback"] == 0
    assert data["wazuh_handoff"]["active_response"] == 0
    assert data["wazuh_handoff"]["agent_visibility_status"] == "blocked_waiting_manager_agent_registry_readback"
    assert data["wazuh_handoff"]["manager_agent_registry_readback_passed"] is False
    assert "base=b540fc0c" in data["wazuh_handoff"]["boundary"]
    assert "release_lane_preflight=ready0_acks0of6_evidence0of6_push0_deploy0_readback0_runtime0" in data["wazuh_handoff"]["boundary"]
    assert "owner_gate=request_sent0_response_accepted0_acks0of6_evidence0of6_push0_deploy0_readback0_runtime0" in data["wazuh_handoff"]["boundary"]
    assert "live_metadata_env_gate=owner0_secret_metadata0_push0_deploy0_readback0_runtime0" in data["wazuh_handoff"]["boundary"]
    assert "wazuh_live_agent_registry_readback=0" in data["wazuh_handoff"]["boundary"]
    assert "manager_agent_registry_readback_passed=false" in data["wazuh_handoff"]["boundary"]
    serialized = json.dumps(data, ensure_ascii=False)
    assert "/Users/ogt" not in serialized
    assert ".claude/projects" not in serialized
    assert {item["gate_id"] for item in data["gate_cards"]} >= {
        "status_cleanup_preflight",
        "owner_review_package",
        "owner_response_preflight",
        "execution_plan",
        "apply_gate",
    }
    assert {item["blocked"] for item in data["gate_cards"]} == {False}


def test_awoooi_status_cleanup_dashboard_rejects_memory_write_authorization(tmp_path):
    snapshot = _snapshot()
    snapshot["memory_write_authorized"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="dashboard boundaries"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def test_awoooi_status_cleanup_dashboard_rejects_wazuh_live_query(tmp_path):
    snapshot = _snapshot()
    snapshot["wazuh_handoff"]["wazuh_api_live_query_authorized"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="Wazuh live query"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def test_awoooi_status_cleanup_dashboard_rejects_live_metadata_gate(tmp_path):
    snapshot = _snapshot()
    snapshot["summary"]["wazuh_live_metadata_owner_count"] = 1
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="Wazuh release summary gates"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def test_awoooi_status_cleanup_dashboard_rejects_controlled_ack_count_drift(tmp_path):
    snapshot = _snapshot()
    snapshot["summary"]["accepted_owner_flag_count"] = 5
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="controlled acknowledgements incomplete"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def test_awoooi_status_cleanup_dashboard_rejects_controlled_flag_drift(tmp_path):
    snapshot = _snapshot()
    snapshot["summary"]["controlled_status_cleanup_package_ready"] = False
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="controlled_status_cleanup_package_ready"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def test_awoooi_status_cleanup_dashboard_rejects_missing_risk_control(tmp_path):
    snapshot = _snapshot()
    snapshot["risk_controls"] = [
        item for item in snapshot["risk_controls"] if item["control_id"] != "host"
    ]
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="risk_controls"):
        load_latest_awoooi_status_cleanup_dashboard(tmp_path)


def _snapshot() -> dict:
    return copy.deepcopy(load_latest_awoooi_status_cleanup_dashboard())


def _write_snapshot(tmp_path, snapshot: dict) -> None:
    (tmp_path / "awoooi-status-cleanup-dashboard.snapshot.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )
