from fastapi.testclient import TestClient

from src.api.v1 import agents as agents_api
from src.main import app
from src.services.ai_agent_autonomous_runtime_control import (
    build_ai_agent_autonomous_runtime_control,
)

_PUBLIC_FORBIDDEN_TERMS = [
    "工作視窗",
    "對話內容",
    "批准！繼續",
    "In app browser",
    "My request for Codex",
    "browser_context",
    "codex_user_message",
    "prompt_text",
    "raw prompt",
    "raw_prompt",
    "raw payload",
    "raw_payload",
    "private reasoning",
    "chain_of_thought",
    "authorization header",
    "authorization_header",
    "secret value",
    "secret_value",
]


def _collect_strings(value):
    if isinstance(value, str):
        return [value]
    if isinstance(value, list):
        strings = []
        for item in value:
            strings.extend(_collect_strings(item))
        return strings
    if isinstance(value, dict):
        strings = []
        for item in value.values():
            strings.extend(_collect_strings(item))
        return strings
    return []


async def _fake_runtime_control_with_live_readback():
    return build_ai_agent_autonomous_runtime_control()


def test_get_ai_agent_autonomous_runtime_control_api(monkeypatch):
    monkeypatch.setattr(
        agents_api,
        "build_ai_agent_autonomous_runtime_control_with_live_readback",
        _fake_runtime_control_with_live_readback,
    )
    client = TestClient(app)
    response = client.get("/api/v1/agents/agent-autonomous-runtime-control")

    assert response.status_code == 200
    data = response.json()
    assert data["schema_version"] == "ai_agent_autonomous_runtime_control_v1"
    assert data["program_status"]["runtime_authority"] == (
        "current_owner_directive_controlled_ai_automation"
    )
    assert data["program_status"]["deploy_readback_marker"] == (
        "p2_416_d1n_autonomous_runtime_control_prod_readback_v2"
    )
    assert data["program_status"]["deploy_attempt_note"] == (
        "cd_internal_control_plane_readback_retry_20260628_2"
    )
    assert data["current_policy"]["owner_review_required_for_low_medium_high"] is False
    assert data["report_delivery"]["status"] == "telegram_gateway_delivery_enabled"
    assert data["rollups"]["report_cadence_enabled_count"] == 3
    assert data["runtime_receipt_readback"]["schema_version"] == (
        "ai_agent_autonomous_runtime_receipt_readback_v1"
    )
    assert data["runtime_receipt_readback"]["db_read_status"] == "not_queried"
    assert data["control_plane_integration"]["status"] == (
        "mcp_rag_km_playbook_log_control_loop_declared"
    )
    assert data["rollups"]["mcp_sensor_count"] == 4
    assert data["rollups"]["deploy_control_classifier_example_count"] == 3


def test_get_ai_agent_autonomous_runtime_control_api_redacts_public_terms(monkeypatch):
    monkeypatch.setattr(
        agents_api,
        "build_ai_agent_autonomous_runtime_control_with_live_readback",
        _fake_runtime_control_with_live_readback,
    )
    client = TestClient(app)
    response = client.get("/api/v1/agents/agent-autonomous-runtime-control")

    assert response.status_code == 200
    all_text = "\n".join(_collect_strings(response.json()))
    for term in _PUBLIC_FORBIDDEN_TERMS:
        assert term not in all_text
