from fastapi.testclient import TestClient

from src.main import app


_PUBLIC_FORBIDDEN_TERMS = [
    "工作視窗",
    "對話內容",
    "批准！繼續",
    "In app browser",
    "My request for Codex",
    "browser_context",
    "codex_user_message",
    "prompt_text",
    "raw payload",
    "raw_payload",
    "private reasoning",
    "chain_of_thought",
    "authorization header",
    "secret value",
    "raw tool output",
    "raw Telegram payload",
    "work window transcript",
    "work_window_transcript",
    "internal collaboration transcript",
]


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 []


def test_get_ai_agent_report_automation_review_api():
    client = TestClient(app)
    response = client.get("/api/v1/agents/agent-report-automation-review")

    assert response.status_code == 200
    data = response.json()
    assert data["schema_version"] == "ai_agent_report_automation_review_v1"
    assert data["program_status"]["current_task_id"] == "P2-403J"
    assert data["program_status"]["next_task_id"] == "P2-403K"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["report_truth"]["daily_report_ready"] is True
    assert data["report_truth"]["weekly_report_ready"] is True
    assert data["report_truth"]["monthly_report_ready"] is True
    assert data["report_truth"]["medium_low_auto_policy_defined"] is True
    assert data["report_truth"]["medium_low_auto_execution_enabled"] is True
    assert data["report_truth"]["low_medium_high_controlled_auto_policy_defined"] is True
    assert data["report_truth"]["high_risk_requires_approval"] is False
    assert data["rollups"]["report_cadence_count"] == 3
    assert data["rollups"]["agent_count"] == 3
    assert data["rollups"]["chart_count"] == 4
    assert data["rollups"]["recommendation_count"] == 5
    assert data["rollups"]["workload_unit_total"] == 91
    assert data["rollups"]["workload_waiting_approval_total"] == 0
    assert data["rollups"]["current_auto_execution_enabled_count"] == 2
    assert data["rollups"]["live_auto_optimization_count"] == 0


def test_get_ai_agent_report_automation_review_api_redacts_public_terms():
    client = TestClient(app)
    response = client.get("/api/v1/agents/agent-report-automation-review")

    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
