from __future__ import annotations

import json

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.telegram_alert_ai_automation_matrix import (
    _inspect_source_contract,
    load_latest_telegram_alert_ai_automation_matrix,
)


def test_telegram_alert_ai_automation_matrix_loader_returns_gap_matrix():
    payload = load_latest_telegram_alert_ai_automation_matrix()

    assert payload["schema_version"] == "telegram_alert_ai_automation_matrix_v1"
    assert payload["priority_work_item_id"] == "CIR-P0-TG-001"
    assert payload["mode"] == "metadata_only_no_secret_no_telegram_send_no_runtime_write"
    assert payload["operation_boundaries"] == {
        "telegram_send_performed": False,
        "bot_api_call_performed": False,
        "gateway_queue_write_performed": False,
        "runtime_write_performed": False,
        "secret_value_read": False,
        "raw_payload_stored": False,
        "receiver_route_changed": False,
        "workflow_dispatch_performed": False,
        "production_write_performed": False,
        "metadata_only": True,
    }

    summary = payload["summary"]
    assert summary["telegram_alert_surface_count"] == 9
    assert summary["known_direct_send_gap_count"] == 0
    assert summary["known_direct_send_gap_file_count"] == 0
    assert summary["workflow_direct_send_gap_count"] == 0
    assert summary["ops_script_direct_send_gap_count"] == 0
    assert summary["api_direct_send_gap_count"] == 0
    assert summary["gateway_normalized_callsite_count"] >= 50
    assert summary["db_or_log_receipt_ready_surface_count"] >= 2
    assert summary["ai_route_ready_surface_count"] >= 3
    assert summary["controlled_queue_ready_surface_count"] >= 2
    assert summary["post_verifier_ready_surface_count"] >= 3
    assert summary["learning_writeback_ready_surface_count"] >= 3
    assert summary["manual_default_gap_count"] == 0
    assert summary["direct_gap_migration_candidate_count"] == 0
    assert summary["owner_acceptance_candidate_count"] == 0
    assert summary["telegram_send_performed_count"] == 0
    assert summary["bot_api_call_performed_count"] == 0
    assert summary["secret_value_read_count"] == 0
    assert summary["runtime_write_performed_count"] == 0
    assert summary["ai_alert_card_delivery_readback_endpoint_count"] == 1
    assert summary["ai_alert_card_learning_writeback_refs_count"] == 1
    assert summary["ai_alert_card_learning_registry_readback_count"] == 1
    assert summary["telegram_alert_ai_loop_consumer_context_readback_count"] == 1
    assert summary["telegram_alert_post_apply_verifier_readback_count"] == 1
    assert summary["telegram_alert_post_apply_verifier_awooop_surface_count"] == 1
    assert summary["source_contract_ready"] is True
    assert summary["source_contract_missing_marker_count"] == 0
    assert summary["source_contract_missing_markers"] == []
    assert summary["next_priority_action_id"] == (
        "audit_all_telegram_monitoring_alerts_db_log_ai_automation_coverage"
    )

    matrix = {item["surface_id"]: item for item in payload["matrix"]}
    assert matrix["telegram_gateway_ai_alert_cards"]["status"] == (
        "ai_controlled_receipt_path_ready"
    )
    assert matrix["telegram_gateway_ai_alert_cards"]["db_or_log_receipt"] == (
        "ready_via_awooop_outbound_message_mirror"
    )
    assert matrix["telegram_direct_bot_api_egress_gap"]["status"] == (
        "gap_closed_no_direct_bot_api_routes_detected"
    )
    assert matrix["telegram_direct_bot_api_egress_gap"]["direct_send_gap_count"] == 0
    assert matrix["telegram_direct_bot_api_egress_gap"]["db_or_log_receipt"] == (
        "ready_no_direct_routes_remaining"
    )
    assert matrix["telegram_egress_controlled_migration_candidates"]["status"] == (
        "controlled_migration_complete_no_candidates"
    )
    assert matrix["telegram_action_required_digest_policy"]["known_item_count"] == 8
    assert matrix["telegram_ai_alert_card_delivery_readback_endpoint"][
        "db_or_log_receipt"
    ] == "ready_awooop_outbound_message_query"
    assert matrix["telegram_ai_alert_card_delivery_readback_endpoint"][
        "learning_writeback"
    ] == "ready_delivery_receipt_summary_and_learning_writeback_refs"
    assert matrix["telegram_alert_learning_registry_readback"]["status"] == (
        "registry_readback_present"
    )
    assert matrix["telegram_alert_learning_registry_readback"]["learning_writeback"] == (
        "ready_km_rag_playbook_mcp_verifier_ai_agent_registry"
    )
    assert matrix["telegram_ai_loop_agent_consumer_context"]["status"] == (
        "ai_loop_context_readback_present"
    )
    assert matrix["telegram_ai_loop_agent_consumer_context"]["ai_route"] == (
        "ready_ai_loop_agent_context_reuse"
    )
    assert matrix["telegram_ai_loop_post_apply_verifier"]["status"] == (
        "post_apply_verifier_readback_present"
    )
    assert matrix["telegram_ai_loop_post_apply_verifier"]["post_verifier"] == (
        "ready_context_receipt_post_apply_verifier"
    )
    assert matrix["telegram_verified_context_awooop_operator_surface"]["status"] == (
        "verified_context_receipt_surface_present"
    )
    assert matrix["telegram_verified_context_awooop_operator_surface"]["ai_route"] == (
        "ready_operator_visible_ai_loop_receipts"
    )

    assert payload["direct_send_gap_refs"] == []
    assert not any(
        ref["path"] == "apps/api/src/services/channel_hub.py"
        for ref in payload["direct_send_gap_refs"]
    )

    serialized = json.dumps(payload, ensure_ascii=False)
    for marker in [
        "TELEGRAM_BOT_TOKEN",
        "authorization_header",
        "raw Telegram payload",
        "批准！繼續",
        "My request for Codex",
    ]:
        assert marker not in serialized


def test_telegram_matrix_source_contract_supports_container_layout(tmp_path):
    (tmp_path / "src/services").mkdir(parents=True)
    (tmp_path / "src/db").mkdir(parents=True)
    (tmp_path / "src/api/v1/platform").mkdir(parents=True)
    (tmp_path / "apps/web/src/components/awooop").mkdir(parents=True)
    (tmp_path / "src/services/telegram_gateway.py").write_text(
        "_mirror_outbound_message\n"
        "record_outbound_message\n"
        "ai_automation_alert_card_mirror_v1\n",
        encoding="utf-8",
    )
    (tmp_path / "src/db/awooop_models.py").write_text(
        '__tablename__ = "awooop_outbound_message"\n',
        encoding="utf-8",
    )
    (tmp_path / "src/api/v1/platform/operator_runs.py").write_text(
        '"/runs/ai-alert-cards"\n'
        "learning_writeback_refs\n"
        "learning_writeback_ready_total\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/platform_operator_service.py").write_text(
        "ai_alert_card_learning_registry_readback_v1\n"
        "ai_agent_context_ref\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/ai_agent_log_controlled_writeback_consumer_readback.py").write_text(
        "telegram_alert_ai_loop_consumer_context_readback_v1\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/telegram_alert_learning_context_post_apply_verifier.py").write_text(
        "telegram_alert_learning_context_post_apply_verifier_v1\n",
        encoding="utf-8",
    )
    (tmp_path / "apps/web/src/components/awooop/autonomous-runtime-receipt-panel.tsx").write_text(
        'data-testid="telegram-alert-post-apply-verifier-readback"\n',
        encoding="utf-8",
    )

    proof = _inspect_source_contract(tmp_path)

    assert proof["telegram_gateway_mirror_present"] is True
    assert proof["telegram_gateway_record_outbound_present"] is True
    assert proof["ai_alert_card_metadata_present"] is True
    assert proof["outbound_message_model_present"] is True
    assert proof["ai_alert_card_delivery_readback_endpoint_present"] is True
    assert proof["ai_alert_card_delivery_readback_endpoint_count"] == 1
    assert proof["ai_alert_card_learning_writeback_refs_present"] is True
    assert proof["ai_alert_card_learning_writeback_refs_count"] == 1
    assert proof["ai_alert_card_learning_registry_readback_present"] is True
    assert proof["ai_alert_card_learning_registry_readback_count"] == 1
    assert proof["ai_alert_card_ai_agent_context_ref_present"] is True
    assert proof["telegram_alert_ai_loop_consumer_context_readback_present"] is True
    assert proof["telegram_alert_ai_loop_consumer_context_readback_count"] == 1
    assert proof["telegram_alert_post_apply_verifier_readback_present"] is True
    assert proof["telegram_alert_post_apply_verifier_readback_count"] == 1
    assert proof["telegram_alert_post_apply_verifier_awooop_surface_present"] is True
    assert proof["telegram_alert_post_apply_verifier_awooop_surface_count"] == 1
    assert proof["source_contract_ready"] is True
    assert proof["source_contract_missing_markers"] == []


def test_telegram_matrix_source_contract_reports_missing_web_surface_without_raising(
    tmp_path,
):
    (tmp_path / "src/services").mkdir(parents=True)
    (tmp_path / "src/db").mkdir(parents=True)
    (tmp_path / "src/api/v1/platform").mkdir(parents=True)
    (tmp_path / "src/services/telegram_gateway.py").write_text(
        "_mirror_outbound_message\n"
        "record_outbound_message\n"
        "ai_automation_alert_card_mirror_v1\n",
        encoding="utf-8",
    )
    (tmp_path / "src/db/awooop_models.py").write_text(
        '__tablename__ = "awooop_outbound_message"\n',
        encoding="utf-8",
    )
    (tmp_path / "src/api/v1/platform/operator_runs.py").write_text(
        '"/runs/ai-alert-cards"\n'
        "learning_writeback_refs\n"
        "learning_writeback_ready_total\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/platform_operator_service.py").write_text(
        "ai_alert_card_learning_registry_readback_v1\n"
        "ai_agent_context_ref\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/ai_agent_log_controlled_writeback_consumer_readback.py").write_text(
        "telegram_alert_ai_loop_consumer_context_readback_v1\n",
        encoding="utf-8",
    )
    (tmp_path / "src/services/telegram_alert_learning_context_post_apply_verifier.py").write_text(
        "telegram_alert_learning_context_post_apply_verifier_v1\n",
        encoding="utf-8",
    )

    proof = _inspect_source_contract(tmp_path)

    assert proof["source_contract_ready"] is False
    assert proof["telegram_alert_post_apply_verifier_awooop_surface_present"] is False
    assert proof["telegram_alert_post_apply_verifier_awooop_surface_count"] == 0
    assert proof["source_contract_missing_markers"] == [
        "telegram_alert_post_apply_verifier_awooop_surface_present"
    ]


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

    response = client.get("/api/v1/agents/telegram-alert-ai-automation-matrix")

    assert response.status_code == 200
    data = response.json()
    assert data["schema_version"] == "telegram_alert_ai_automation_matrix_v1"
    assert data["summary"]["known_direct_send_gap_count"] == 0
    assert data["summary"]["next_priority_work_item_id"] == "CIR-P0-TG-001"
    assert data["operation_boundaries"]["telegram_send_performed"] is False
    assert data["operation_boundaries"]["secret_value_read"] is False
