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_feedback_receipt_dry_run import (
    load_latest_ai_agent_log_feedback_receipt_dry_run,
)


def test_log_feedback_receipt_dry_run_loader_builds_candidate_receipts():
    payload = load_latest_ai_agent_log_feedback_receipt_dry_run()

    _assert_feedback_dry_run_payload(payload)


def test_log_feedback_receipt_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-feedback-receipt-dry-run")

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


def _assert_feedback_dry_run_payload(payload: dict):
    expected_source_sample_ids = {
        "api_structured_log_chain_sample",
        "p0_110_harbor_runner_control_path_sample",
        "worker_mcp_registry_runtime_sample",
    }
    expected_runtime_sample_count = len(expected_source_sample_ids)
    expected_target_count = 6

    assert payload["schema_version"] == "ai_agent_log_feedback_receipt_dry_run_v1"
    assert payload["priority"] == "P1-LOG-KM-RAG-MCP-PLAYBOOK"
    assert payload["status"] == "trusted_feedback_receipt_dry_run_ready"
    assert payload["active_blockers"] == []
    assert payload["readback"]["source_status"] == (
        "controlled_apply_ready_for_trusted_feedback_receipt"
    )
    assert payload["readback"]["safe_next_step"] == (
        "enable_post_write_verifier_for_km_rag_playbook_trust_receipts"
    )

    assert payload["rollups"]["pipeline_node_count"] == 9
    assert payload["rollups"]["completed_node_count"] == 9
    assert payload["rollups"]["target_count"] == expected_target_count
    assert payload["rollups"]["runtime_sample_count"] == expected_runtime_sample_count
    assert payload["rollups"]["candidate_receipt_count"] == (
        expected_runtime_sample_count * expected_target_count
    )
    assert payload["rollups"]["km_candidate_count"] == expected_runtime_sample_count
    assert payload["rollups"]["rag_candidate_count"] == expected_runtime_sample_count
    assert payload["rollups"]["playbook_candidate_count"] == expected_runtime_sample_count
    assert payload["rollups"]["mcp_candidate_count"] == expected_runtime_sample_count
    assert payload["rollups"]["verifier_candidate_count"] == expected_runtime_sample_count
    assert (
        payload["rollups"]["ai_agent_context_candidate_count"]
        == expected_runtime_sample_count
    )
    assert payload["rollups"]["dry_run_ready"] is True

    nodes = {node["node_id"]: node for node in payload["pipeline_nodes"]}
    assert nodes["collect_labeled_runtime_logs"]["stage"] == "ingest"
    assert nodes["build_km_memory_candidates"]["target"] == "km"
    assert nodes["build_rag_chunk_candidates"]["target"] == "rag"
    assert nodes["build_playbook_trust_candidates"]["target"] == "playbook"
    assert nodes["build_mcp_audit_feedback_candidates"]["target"] == "mcp"
    assert nodes["publish_agent_decision_context_dry_run"]["target"] == "ai_agent"
    assert all(node["status"] == "dry_run_ready" for node in nodes.values())
    assert all(node["write_enabled"] is False for node in nodes.values())

    receipts = payload["candidate_receipts"]
    targets = {receipt["target"] for receipt in receipts}
    assert targets == {"km", "rag", "playbook", "mcp", "verifier", "ai_agent"}
    assert all(receipt["dry_run_status"] == "candidate_ready" for receipt in receipts)
    assert all(receipt["write_enabled"] is False for receipt in receipts)
    assert all(receipt["raw_log_payload_persisted"] is False for receipt in receipts)
    assert {receipt["source_sample_id"] for receipt in receipts} == expected_source_sample_ids
    p0_receipts = [
        receipt
        for receipt in receipts
        if receipt["source_sample_id"] == "p0_110_harbor_runner_control_path_sample"
    ]
    assert len(p0_receipts) == 6
    assert {receipt["target"] for receipt in p0_receipts} == targets
    assert {receipt["service"] for receipt in p0_receipts} == {
        "awoooi-110-control-path"
    }
    assert {
        receipt["classification"]["current_blocker"] for receipt in p0_receipts
    } == {"controlled_cd_lane_guardrails_blocked"}
    assert {
        receipt["classification"]["controlled_recovery_package"]
        for receipt in p0_receipts
    } == {"check-awoooi-110-controlled-cd-lane-readiness.sh"}
    assert {
        receipt["classification"]["post_apply_verifier"] for receipt in p0_receipts
    } == {"harbor-registry-controlled-recovery-receipt validator"}
    assert all(
        len(receipt["classification"]["controlled_local_console_execution_plan"]) == 3
        for receipt in p0_receipts
    )
    assert all(
        receipt["classification"]["controlled_local_console_execution_plan"][2][
            "command"
        ]
        == "check-awoooi-110-controlled-cd-lane-readiness.sh"
        for receipt in p0_receipts
    )
    assert all(
        len(receipt["classification"]["post_recovery_readback_commands"]) == 3
        for receipt in p0_receipts
    )
    assert all(
        "restart_docker_daemon"
        in receipt["classification"]["forbidden_runtime_actions"]
        for receipt in p0_receipts
    )

    boundaries = payload["operation_boundaries"]
    assert boundaries["dry_run_only"] 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_apply_verifier_executed"] 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
