from __future__ import annotations

import json

import pytest

from src.services.ai_agent_telegram_action_required_digest_policy import (
    load_latest_ai_agent_telegram_action_required_digest_policy,
)


def test_load_latest_ai_agent_telegram_action_required_digest_policy_reads_committed_snapshot():
    data = load_latest_ai_agent_telegram_action_required_digest_policy()

    assert data["schema_version"] == "ai_agent_telegram_action_required_digest_policy_v1"
    assert data["program_status"]["overall_completion_percent"] == 68
    assert data["program_status"]["current_task_id"] == "P2-402D"
    assert data["program_status"]["next_task_id"] == "P2-402E"
    assert data["program_status"]["read_only_mode"] is True
    assert data["program_status"]["runtime_authority"] == "policy_only_no_telegram_send_or_route_change"
    assert data["operation_boundaries"]["read_only_policy_allowed"] is True
    assert data["operation_boundaries"]["telegram_direct_send_allowed"] is False
    assert data["operation_boundaries"]["telegram_gateway_queue_write_allowed"] is False
    assert data["operation_boundaries"]["alertmanager_route_change_allowed"] is False
    assert data["operation_boundaries"]["conversation_transcript_allowed"] is False
    assert data["approval_boundaries"]["telegram_digest_send_approved"] is False
    assert data["rollups"]["rule_count"] == len(data["digest_rules"]) == 8
    assert data["rollups"]["channel_count"] == len(data["digest_channels"]) == 3
    assert data["rollups"]["trigger_category_count"] == len(data["trigger_categories"]) == 5
    assert data["rollups"]["by_decision"]["suppress_success_noise"] == 2
    assert data["rollups"]["by_decision"]["draft_failure_escalation_digest"] == 3
    assert data["rollups"]["by_decision"]["draft_action_required_digest"] == 3
    assert data["rollups"]["telegram_direct_send_allowed_count"] == 0
    assert data["rollups"]["telegram_gateway_queue_write_allowed_count"] == 0
    assert data["rollups"]["route_change_allowed_count"] == 0
    assert data["rollups"]["conversation_transcript_allowed_count"] == 0
    assert "work_window_transcript" in data["message_template_contract"]["forbidden_fields"]
    assert all(
        rule["decision"] == "suppress_success_noise"
        for rule in data["digest_rules"]
        if rule["signal_state"] in {"success", "verified"}
    )


def test_ai_agent_telegram_action_required_digest_policy_blocks_direct_send(tmp_path):
    snapshot = _snapshot()
    snapshot["operation_boundaries"]["telegram_direct_send_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="operation boundaries"):
        load_latest_ai_agent_telegram_action_required_digest_policy(tmp_path)


def test_ai_agent_telegram_action_required_digest_policy_rejects_rollup_mismatch(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["rule_count"] = 99
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="rollup counts"):
        load_latest_ai_agent_telegram_action_required_digest_policy(tmp_path)


def test_ai_agent_telegram_action_required_digest_policy_rejects_success_noise(tmp_path):
    snapshot = _snapshot()
    snapshot["digest_rules"][0]["decision"] = "draft_action_required_digest"
    snapshot["digest_rules"][0]["requires_openclaw_review"] = True
    snapshot["rollups"]["by_decision"] = {
        "draft_action_required_digest": 2,
        "draft_failure_escalation_digest": 1,
    }
    snapshot["rollups"]["action_required_rule_ids"] = [
        "repo_only_freshness_snapshot_success",
        "tool_install_or_ci_change_needs_approval",
    ]
    snapshot["rollups"]["suppressed_success_rule_ids"] = []
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="success/verified signals"):
        load_latest_ai_agent_telegram_action_required_digest_policy(tmp_path)


def test_ai_agent_telegram_action_required_digest_policy_rejects_transcript_markers(tmp_path):
    snapshot = _snapshot()
    snapshot["message_template_contract"]["action_required_message_policy"] = (
        "禁止放入：" + "My request for Codex"
    )
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden work-window conversation content"):
        load_latest_ai_agent_telegram_action_required_digest_policy(tmp_path)


def test_ai_agent_telegram_action_required_digest_policy_requires_redaction_fields(tmp_path):
    snapshot = _snapshot()
    snapshot["message_template_contract"]["forbidden_fields"].remove("work_window_transcript")
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden_fields"):
        load_latest_ai_agent_telegram_action_required_digest_policy(tmp_path)


def _write_snapshot(tmp_path, snapshot: dict) -> None:
    (tmp_path / "ai_agent_telegram_action_required_digest_policy_2026-06-11.json").write_text(
        json.dumps(snapshot),
        encoding="utf-8",
    )


def _snapshot() -> dict:
    return {
        "schema_version": "ai_agent_telegram_action_required_digest_policy_v1",
        "generated_at": "2026-06-11T23:58:00+08:00",
        "program_status": {
            "overall_completion_percent": 68,
            "current_priority": "P2",
            "current_task_id": "P2-402D",
            "next_task_id": "P2-402E",
            "read_only_mode": True,
            "runtime_authority": "policy_only_no_telegram_send_or_route_change",
            "status_note": "測試。",
        },
        "source_refs": ["docs/evaluations/example.json"],
        "trigger_categories": [
            {
                "category_id": "success_noise",
                "owner_agent": "Hermes",
                "policy_intent": "測試。",
                "blocked_now": ["send"],
            },
            {
                "category_id": "tool_adoption_approval_required",
                "owner_agent": "OpenClaw",
                "policy_intent": "測試。",
                "blocked_now": ["send"],
            },
        ],
        "digest_channels": [
            {
                "channel_id": "telegram_ops_digest_draft",
                "purpose": "測試。",
                "success_immediate_allowed": False,
                "direct_send_allowed": False,
                "queue_write_allowed": False,
                "requires_telegram_gateway_e2e": True,
            }
        ],
        "digest_rules": [
            {
                "rule_id": "repo_only_freshness_snapshot_success",
                "category_id": "success_noise",
                "signal_state": "success",
                "severity": "info",
                "decision": "suppress_success_noise",
                "owner_agent": "Hermes",
                "required_evidence": ["snapshot"],
                "channels": ["telegram_ops_digest_draft"],
                "requires_openclaw_review": False,
                "telegram_direct_send_allowed": False,
                "next_action": "測試。",
            },
            {
                "rule_id": "version_watch_source_failed",
                "category_id": "tool_adoption_approval_required",
                "signal_state": "failed",
                "severity": "warning",
                "decision": "draft_failure_escalation_digest",
                "owner_agent": "Hermes",
                "required_evidence": ["source_id"],
                "channels": ["telegram_ops_digest_draft"],
                "requires_openclaw_review": True,
                "telegram_direct_send_allowed": False,
                "next_action": "測試。",
            },
            {
                "rule_id": "tool_install_or_ci_change_needs_approval",
                "category_id": "tool_adoption_approval_required",
                "signal_state": "action_required",
                "severity": "warning",
                "decision": "draft_action_required_digest",
                "owner_agent": "OpenClaw",
                "required_evidence": ["tool_id"],
                "channels": ["telegram_ops_digest_draft"],
                "requires_openclaw_review": True,
                "telegram_direct_send_allowed": False,
                "next_action": "測試。",
            },
        ],
        "message_template_contract": {
            "required_fields": [
                "stage",
                "severity",
                "target_id",
                "evidence_ref",
                "blocked_reason",
                "next_action",
                "owner_agent",
                "approval_gate",
            ],
            "forbidden_fields": [
                "secret_value",
                "token",
                "authorization_header",
                "work_window_transcript",
                "codex_user_message",
                "prompt_text",
                "chain_of_thought",
                "session_id",
                "browser_context",
            ],
            "success_message_policy": "成功不得送 Telegram。",
            "action_required_message_policy": "測試。",
            "failure_message_policy": "測試。",
        },
        "rate_limit_policy": {
            "success_policy": "成功不得 Telegram 洗版。",
            "digest_window_minutes": 30,
            "dedupe_key_fields": ["category_id"],
            "max_digest_items": 10,
            "fallback_policy": "測試。",
        },
        "display_redaction_contract": {
            "conversation_transcript_display_allowed": False,
            "redaction_required": True,
            "allowed_frontend_fields": ["政策規則摘要"],
            "forbidden_frontend_content": ["內部對話內容"],
        },
        "agent_roles": [],
        "operation_boundaries": {
            "read_only_policy_allowed": True,
            "telegram_direct_send_allowed": False,
            "telegram_test_message_allowed": False,
            "telegram_gateway_queue_write_allowed": False,
            "alertmanager_route_change_allowed": False,
            "telegram_receiver_change_allowed": False,
            "awooop_event_write_allowed": False,
            "workflow_trigger_allowed": False,
            "external_scan_allowed": False,
            "runtime_execution_allowed": False,
            "secret_plaintext_allowed": False,
            "conversation_transcript_allowed": False,
        },
        "approval_boundaries": {
            "telegram_digest_send_approved": False,
            "telegram_gateway_queue_write_approved": False,
            "telegram_route_change_approved": False,
            "alertmanager_receiver_change_approved": False,
            "awooop_event_write_approved": False,
            "workflow_trigger_approved": False,
            "runtime_execution_approved": False,
            "secret_plaintext_approved": False,
        },
        "rollups": {
            "rule_count": 3,
            "channel_count": 1,
            "trigger_category_count": 2,
            "by_decision": {
                "suppress_success_noise": 1,
                "draft_failure_escalation_digest": 1,
                "draft_action_required_digest": 1,
            },
            "action_required_rule_ids": ["tool_install_or_ci_change_needs_approval"],
            "failure_escalation_rule_ids": ["version_watch_source_failed"],
            "suppressed_success_rule_ids": ["repo_only_freshness_snapshot_success"],
            "telegram_direct_send_allowed_count": 0,
            "telegram_gateway_queue_write_allowed_count": 0,
            "route_change_allowed_count": 0,
            "conversation_transcript_allowed_count": 0,
            "next_approval_task_ids": ["P2-402E"],
        },
    }
