from __future__ import annotations

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.ai_agent_log_post_write_verifier_dry_run import (
    load_latest_ai_agent_log_post_write_verifier_dry_run,
)


def test_log_post_write_verifier_dry_run_loader_verifies_all_targets():
    payload = load_latest_ai_agent_log_post_write_verifier_dry_run()

    _assert_post_write_verifier_payload(payload)


def test_log_post_write_verifier_dry_run_endpoint_returns_readback():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get("/api/v1/agents/agent-log-post-write-verifier-dry-run")

    assert response.status_code == 200
    _assert_post_write_verifier_payload(response.json())


def _assert_post_write_verifier_payload(payload: dict):
    expected_runtime_sample_count = 3
    expected_target_count = 6
    expected_candidate_receipt_count = (
        expected_runtime_sample_count * expected_target_count
    )

    assert payload["schema_version"] == "ai_agent_log_post_write_verifier_dry_run_v1"
    assert payload["priority"] == "P1-LOG-KM-RAG-MCP-PLAYBOOK"
    assert payload["status"] == "post_write_verifier_dry_run_ready"
    assert payload["active_blockers"] == []
    assert payload["readback"]["source_status"] == "trusted_feedback_receipt_dry_run_ready"
    assert payload["readback"]["safe_next_step"] == (
        "enable_controlled_km_rag_playbook_trust_writeback_with_post_write_verifier"
    )

    assert payload["rollups"]["verifier_node_count"] == 6
    assert payload["rollups"]["passed_verifier_node_count"] == 6
    assert payload["rollups"]["target_count"] == expected_target_count
    assert payload["rollups"]["verified_target_count"] == expected_target_count
    assert (
        payload["rollups"]["candidate_receipt_count"]
        == expected_candidate_receipt_count
    )
    assert (
        payload["rollups"]["verified_candidate_receipt_count"]
        == expected_candidate_receipt_count
    )
    assert payload["rollups"]["source_pipeline_node_count"] == 9
    assert (
        payload["rollups"]["source_candidate_receipt_count"]
        == expected_candidate_receipt_count
    )
    assert payload["rollups"]["runtime_sample_count"] == expected_runtime_sample_count
    assert payload["rollups"]["dry_run_ready"] is True
    assert payload["rollups"]["controlled_writeback_next_step_ready"] is True
    assert payload["rollups"]["writeback_authorized_by_this_endpoint"] is False

    nodes = {node["node_id"]: node for node in payload["verifier_nodes"]}
    assert set(nodes) == {
        "verify_km_memory_receipt_shape",
        "verify_rag_chunk_receipt_shape",
        "verify_playbook_trust_receipt_shape",
        "verify_mcp_audit_feedback_shape",
        "verify_post_apply_feedback_binding",
        "verify_agent_decision_context_binding",
    }
    assert all(node["status"] == "dry_run_passed" for node in nodes.values())
    assert all(node["write_enabled"] is False for node in nodes.values())
    assert all(
        node["requires_controlled_writeback_verifier"] is True
        for node in nodes.values()
    )

    verifications = {
        verification["target"]: verification
        for verification in payload["target_verifications"]
    }
    assert set(verifications) == {"km", "rag", "playbook", "mcp", "verifier", "ai_agent"}
    for verification in verifications.values():
        assert verification["status"] == "target_receipts_verified"
        assert verification["candidate_count"] == expected_runtime_sample_count
        assert verification["verified_candidate_count"] == expected_runtime_sample_count
        assert verification["invalid_candidate_count"] == 0
        assert verification["invalid_receipts"] == []
        assert verification["write_enabled"] is False
        assert {
            "receipt_id",
            "source_sample_id",
            "project_id",
            "product",
            "service",
            "package",
            "tool",
            "source_system",
            "redaction_state",
            "observed_event_count",
            "observed_field_count",
            "dry_run_status",
            "write_enabled",
            "raw_log_payload_persisted",
        }.issubset(set(verification["required_fields"]))

    boundaries = payload["operation_boundaries"]
    assert boundaries["dry_run_only"] is True
    assert boundaries["post_write_verifier_dry_run_performed"] is True
    assert boundaries["km_write_performed"] is False
    assert boundaries["rag_index_write_performed"] is False
    assert boundaries["playbook_trust_write_performed"] is False
    assert boundaries["mcp_tool_call_performed"] is False
    assert boundaries["agent_runtime_action_performed"] is False
    assert boundaries["post_write_verifier_runtime_write_performed"] is False
    assert boundaries["raw_log_payload_persisted"] is False
    assert boundaries["secret_value_collection_allowed"] is False
    assert boundaries["workflow_trigger_performed"] is False
    assert boundaries["github_api_used"] is False
