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_intelligence_integration_readback import (
    _ref_exists,
    load_latest_ai_agent_log_intelligence_integration_readback,
)


def test_ai_agent_log_intelligence_integration_loader_maps_all_lanes():
    payload = load_latest_ai_agent_log_intelligence_integration_readback()

    _assert_log_intelligence_payload(payload)


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

    response = client.get(
        "/api/v1/agents/agent-log-intelligence-integration-readback"
    )

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


def test_log_intelligence_ref_exists_supports_api_container_layout(tmp_path):
    container_ref = tmp_path / "src" / "services" / "diagnosis_aggregator.py"
    container_ref.parent.mkdir(parents=True)
    container_ref.write_text("# packaged API source\n", encoding="utf-8")

    assert _ref_exists(
        tmp_path,
        "apps/api/src/services/diagnosis_aggregator.py",
    )


def _assert_log_intelligence_payload(payload: dict):
    assert (
        payload["schema_version"]
        == "ai_agent_log_intelligence_integration_readback_v1"
    )
    assert payload["priority"] == "P1-LOG-KM-RAG-MCP-PLAYBOOK"
    assert payload["status"] == "controlled_apply_ready_for_trusted_feedback_receipt"
    assert payload["rollups"]["lane_count"] == 7
    assert payload["rollups"]["ready_lane_count"] == 7
    assert payload["rollups"]["missing_lane_count"] == 0
    assert payload["rollups"]["readiness_percent"] == 100
    assert payload["rollups"]["runtime_e2e_log_sample_readback_present"] is True
    assert payload["rollups"]["runtime_sample_count"] == 3
    assert payload["rollups"]["current_p0_blocker_runtime_sample_present"] is True
    assert payload["rollups"]["controlled_recovery_package_sample_present"] is True
    assert payload["rollups"]["km_rag_feedback_receipt_ready"] is True
    assert payload["rollups"]["playbook_feedback_receipt_ready"] is True
    assert payload["rollups"]["mcp_audit_feedback_receipt_ready"] is True
    assert payload["rollups"]["km_rag_playbook_trust_writeback_authorized"] is False
    assert payload["rollups"]["mcp_tool_execution_authorized"] is False
    assert payload["active_blockers"] == []
    assert payload["runtime_e2e_verifier"]["schema_version"] == (
        "ai_agent_log_intelligence_runtime_sample_readback_v1"
    )
    assert payload["runtime_e2e_verifier"]["label_receipt"]["runtime_sample_count"] == 3
    assert payload["runtime_e2e_verifier"]["operation_boundaries"][
        "runtime_log_sample_read_performed"
    ] is True
    assert payload["runtime_e2e_verifier"]["operation_boundaries"][
        "raw_log_payload_persisted"
    ] is False

    lanes = {lane["lane_id"]: lane for lane in payload["integration_lanes"]}
    assert set(lanes) == {
        "structured_service_log_collection",
        "log_classification_summary",
        "km_rag_consumption",
        "playbook_learning_loop",
        "mcp_tool_audit_context",
        "agent_decision_runtime_context",
        "post_apply_verifier_feedback",
    }
    assert "apps/api/src/services/diagnosis_aggregator.py" in lanes[
        "structured_service_log_collection"
    ]["evidence_refs"]
    assert "apps/api/src/services/knowledge_rag_service.py" in lanes[
        "km_rag_consumption"
    ]["evidence_refs"]
    assert "apps/api/src/services/playbook_rag.py" in lanes[
        "playbook_learning_loop"
    ]["evidence_refs"]
    assert "apps/api/src/plugins/mcp/mcp_bridge.py" in lanes[
        "mcp_tool_audit_context"
    ]["evidence_refs"]
    assert all(lane["runtime_write_enabled"] is False for lane in lanes.values())
    assert all(not lane["missing_refs"] for lane in lanes.values())

    samples = {
        sample["sample_id"]: sample
        for sample in payload["runtime_e2e_verifier"]["samples"]
    }
    p0_sample = samples["p0_110_harbor_runner_control_path_sample"]
    assert p0_sample["service"] == "awoooi-110-control-path"
    assert p0_sample["classification"]["current_blocker"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert p0_sample["classification"]["ssh_auth_classification"] == (
        "ssh_control_path_ready"
    )
    assert p0_sample["classification"]["remote_control_channel"] == "available"
    assert p0_sample["classification"]["bounded_ssh_timeout_seen"] is False
    assert p0_sample["classification"]["remote_ssh_publickey_auth_stalled"] is False
    assert (
        p0_sample["classification"][
            "remote_ssh_publickey_offer_timeout"
        ]
        is False
    )
    assert (
        p0_sample["classification"][
            "remote_ssh_server_accepts_key_then_session_timeout"
        ]
        is False
    )
    assert p0_sample["classification"]["remote_ssh_auth_permission_denied"] is False
    assert p0_sample["classification"]["remote_ssh_reachable"] is True
    assert p0_sample["classification"]["controlled_recovery_package"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert p0_sample["classification"]["post_apply_verifier"] == (
        "harbor-registry-controlled-recovery-receipt validator"
    )
    recovery_plan = p0_sample["classification"][
        "controlled_local_console_execution_plan"
    ]
    assert [phase["phase_id"] for phase in recovery_plan] == [
        "verify_ssh_control_path_restored",
        "verify_harbor_v2_ready",
        "verify_controlled_cd_lane_guardrails",
    ]
    assert recovery_plan[0]["mode"] == "read_only"
    assert recovery_plan[0]["expected_result"] == (
        "ssh_local_repair_control_channel_metadata_ready_and_no_secret_output"
    )
    assert recovery_plan[2]["mode"] == "post_apply_verifier"
    assert recovery_plan[2]["expected_result"] == (
        "config_binary_registration_service_pressure_guardrails_classified_without_runner_token_read"
    )
    assert recovery_plan[2]["runtime_write_allowed_only_on_110_local_console"] is False
    assert "check-awoooi-110-controlled-cd-lane-readiness.sh" in p0_sample[
        "classification"
    ]["post_recovery_readback_commands"]
    assert "read_runner_registration_token_or_runner_file" in p0_sample[
        "classification"
    ]["forbidden_runtime_actions"]
    assert p0_sample["raw_log_payload_persisted"] is False

    label_groups = {
        group["label_group"]: set(group["required_fields"])
        for group in payload["label_taxonomy"]
    }
    assert {"project_id", "product", "service"}.issubset(
        label_groups["ownership"]
    )
    assert {"package", "tool", "source_system"}.issubset(
        label_groups["runtime_surface"]
    )
    assert {"trace_id", "incident_id", "agent_run_id"}.issubset(
        label_groups["correlation"]
    )
    assert {"playbook_id", "verifier_id", "risk_tier"}.issubset(
        label_groups["learning"]
    )

    boundaries = payload["operation_boundaries"]
    assert boundaries["read_only_api_allowed"] is True
    assert boundaries["live_log_query_performed"] is False
    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["runtime_repair_performed"] is False
    assert boundaries["secret_value_collection_allowed"] is False
    assert boundaries["raw_session_or_sqlite_read_allowed"] is False
    assert boundaries["github_api_used"] is False
