"""候選審核 queue AI summary persistence Telegram dispatch gate preview。

本模組只在 summary persistence closeout 之後整理 Telegram 派送前置 gate；
不讀 approval token、不呼叫 LLM、不派送 Telegram、不開 DB、不寫檔、
不更新 review_state、不 commit、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-token",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
    "telegram_token_present",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
REQUIRED_CLOSEOUT_BOUNDARIES = {
    "do_not_execute_summary_persistence_writer_from_closeout_api",
    "do_not_read_approval_token_from_summary_persistence_closeout_api",
    "do_not_write_closeout_artifact_from_summary_persistence_closeout_api",
    "do_not_open_database_connection_from_summary_persistence_closeout",
    "do_not_write_metadata_json_from_summary_persistence_closeout",
    "do_not_update_review_state_from_summary_persistence_closeout",
    "do_not_dispatch_telegram_from_summary_persistence_closeout",
    "do_not_attach_scheduler_from_summary_persistence_closeout",
    "future_telegram_dispatch_must_use_separate_gate",
}
TARGET_TABLE = "market_alert_review_queue"
TARGET_COLUMN = "metadata_json"
SUMMARY_METADATA_KEY = "ai_summary_review"


def _as_dict(value):
    return value if isinstance(value, dict) else {}


def _as_list(value):
    if value is None:
        return []
    if isinstance(value, (list, tuple, set)):
        return list(value)
    return [value]


def _has_text(value):
    return bool(isinstance(value, str) and value.strip())


def _safe_text(value, limit=300):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _contains_forbidden_token_key(value):
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in SAFE_TOKEN_METADATA_KEYS and isinstance(nested, bool):
                continue
            if normalized_key == "approval_env_var" and nested == SAFE_APPROVAL_ENV_VAR:
                continue
            if any(token_key in normalized_key for token_key in FORBIDDEN_TOKEN_KEYWORDS):
                return True
            if _contains_forbidden_token_key(nested):
                return True
    elif isinstance(value, list):
        return any(_contains_forbidden_token_key(item) for item in value)
    return False


def _closeout_summary(closeout):
    closeout = _as_dict(closeout)
    promotion = _as_dict(closeout.get("promotion_gate"))
    receipt = _as_dict(closeout.get("receipt_summary"))
    expected_keys = _as_list(receipt.get("expected_dedupe_key_count"))
    if isinstance(receipt.get("expected_dedupe_key_count"), int):
        expected_key_count = receipt.get("expected_dedupe_key_count")
    else:
        expected_key_count = len(expected_keys)
    safe_boundaries = set(str(item) for item in _as_list(closeout.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_CLOSEOUT_BOUNDARIES - safe_boundaries)

    return {
        "provided": bool(closeout),
        "mode": closeout.get("mode"),
        "target_operation": closeout.get("target_operation"),
        "target_json_path": _as_list(closeout.get("target_json_path")),
        "closeout_passed": bool(
            closeout.get("closeout_passed")
            and closeout.get("summary_persistence_closeout_passed")
        ),
        "ready_for_summary_persistence_telegram_dispatch_gate": bool(
            closeout.get("ready_for_summary_persistence_telegram_dispatch_gate")
        ),
        "ready_for_next_manual_phase": bool(closeout.get("ready_for_next_manual_phase")),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "telegram_dispatch_requires_separate_gate": bool(
            promotion.get("telegram_dispatch_requires_separate_gate")
        ),
        "expected_dedupe_key_count": int(expected_key_count or 0),
        "expected_summary_payload_hash": receipt.get("expected_summary_payload_hash"),
        "writer_metadata_json_update_executed": bool(
            receipt.get("writer_metadata_json_update_executed")
        ),
        "postwrite_smoke_metadata_json_verified": bool(
            receipt.get("postwrite_smoke_metadata_json_verified")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "ready_for_api_database_write": bool(closeout.get("ready_for_api_database_write")),
        "ready_for_telegram_dispatch": bool(closeout.get("ready_for_telegram_dispatch")),
        "ready_for_scheduler_attach": bool(closeout.get("ready_for_scheduler_attach")),
        "api_executes_cli": bool(closeout.get("api_executes_cli")),
        "api_executes_llm": bool(closeout.get("api_executes_llm")),
        "api_reads_approval_token": bool(closeout.get("api_reads_approval_token")),
        "api_writes_file": bool(closeout.get("api_writes_file")),
        "api_writes_database": bool(closeout.get("api_writes_database")),
        "api_updates_review_state": bool(closeout.get("api_updates_review_state")),
        "summary_persistence_closeout_file_written": bool(
            closeout.get("summary_persistence_closeout_file_written")
        ),
        "summary_persistence_record_written": bool(
            closeout.get("summary_persistence_record_written")
        ),
        "metadata_patch_written": bool(closeout.get("metadata_patch_written")),
        "llm_call_executed": bool(closeout.get("llm_call_executed")),
        "telegram_dispatched": bool(closeout.get("telegram_dispatched")),
        "database_connection_opened": bool(closeout.get("database_connection_opened")),
        "database_write_executed": bool(closeout.get("database_write_executed")),
        "database_commit_executed": bool(closeout.get("database_commit_executed")),
        "review_state_update_executed": bool(
            closeout.get("review_state_update_executed")
        ),
        "scheduler_attached": bool(closeout.get("scheduler_attached")),
    }


def _operator_gate_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    channel_label = _safe_text(
        operator_evidence.get("telegram_channel_label")
        or operator_evidence.get("telegram_dispatch_channel")
        or operator_evidence.get("notification_channel")
    )
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "telegram_dispatch_gate_artifact_path_recorded": _has_text(
            operator_evidence.get("ai_summary_telegram_dispatch_gate_artifact_path")
            or operator_evidence.get("telegram_dispatch_gate_artifact_path")
            or operator_evidence.get("dispatch_gate_artifact_path")
        ),
        "operator_confirmed_summary_persistence_telegram_dispatch_gate": bool(
            operator_evidence.get(
                "operator_confirmed_summary_persistence_telegram_dispatch_gate"
            )
            or operator_evidence.get("operator_confirmed_telegram_dispatch_gate")
        ),
        "operator_confirmed_telegram_message_reviewed": bool(
            operator_evidence.get("operator_confirmed_telegram_message_reviewed")
        ),
        "operator_confirmed_dispatch_requires_manual_run_package": bool(
            operator_evidence.get(
                "operator_confirmed_dispatch_requires_manual_run_package"
            )
            or operator_evidence.get("operator_confirmed_telegram_dispatch_requires_run_package")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
            or operator_evidence.get("operator_confirmed_no_telegram_dispatch")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "telegram_channel_label_recorded": bool(channel_label),
        "telegram_channel_label": channel_label,
        "dispatch_notes_recorded": _has_text(operator_evidence.get("dispatch_notes")),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _dispatch_message_contract(closeout_summary, operator):
    return {
        "source_table": TARGET_TABLE,
        "source_column": TARGET_COLUMN,
        "source_json_path": [SUMMARY_METADATA_KEY],
        "source_operation": "read_persisted_ai_summary_review",
        "target_channel": operator["telegram_channel_label"] or "telegram_manual_gate",
        "message_format": "market_intel_ai_summary_brief",
        "max_message_chars": 3500,
        "requires_evidence_refs": True,
        "requires_dedupe_key_summary": True,
        "requires_summary_payload_hash": True,
        "expected_dedupe_key_count": closeout_summary["expected_dedupe_key_count"],
        "expected_summary_payload_hash": closeout_summary[
            "expected_summary_payload_hash"
        ],
        "api_dispatches_telegram": False,
        "scheduler_dispatches_telegram": False,
        "approval_tokens_allowed_in_message": False,
    }


def _gate_checks(closeout_summary, operator, message_contract, apply_real_write):
    return [
        {
            "key": "summary_persistence_closeout_preview_provided",
            "label": "必須提供 summary persistence closeout preview",
            "passed": bool(
                closeout_summary["provided"]
                and closeout_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_run_closeout_preview"
            ),
        },
        {
            "key": "summary_persistence_closeout_passed",
            "label": "closeout 必須已通過且只放行到 Telegram dispatch gate",
            "passed": bool(
                closeout_summary["closeout_passed"]
                and closeout_summary[
                    "ready_for_summary_persistence_telegram_dispatch_gate"
                ]
                and closeout_summary["ready_for_next_manual_phase"]
                and closeout_summary["promotion_allowed"]
                and closeout_summary["promotion_next_manual_phase"]
                == "summary_persistence_telegram_dispatch_gate"
            ),
        },
        {
            "key": "summary_persistence_target_locked",
            "label": "上游資料來源必須鎖定 metadata_json.ai_summary_review",
            "passed": bool(
                closeout_summary["target_operation"]
                == "persist_ai_summary_metadata_json"
                and SUMMARY_METADATA_KEY in closeout_summary["target_json_path"]
            ),
        },
        {
            "key": "telegram_dispatch_separate_gate_confirmed",
            "label": "closeout promotion 必須明確要求 Telegram dispatch 另開 gate",
            "passed": closeout_summary["telegram_dispatch_requires_separate_gate"],
        },
        {
            "key": "summary_persistence_evidence_present",
            "label": "dispatch gate 必須保有 dedupe key、summary hash 與 metadata_json smoke 證據",
            "passed": bool(
                closeout_summary["expected_dedupe_key_count"]
                and closeout_summary["expected_summary_payload_hash"]
                and closeout_summary["writer_metadata_json_update_executed"]
                and closeout_summary["postwrite_smoke_metadata_json_verified"]
            ),
        },
        {
            "key": "closeout_safe_boundaries_complete",
            "label": "closeout 必須保留不派送 Telegram、不掛 scheduler 的安全邊界",
            "passed": closeout_summary["safe_boundaries_complete"],
        },
        {
            "key": "closeout_had_no_api_side_effects",
            "label": "dispatch gate 前不得已有 API DB/檔案/LLM/Telegram/scheduler 副作用",
            "passed": bool(
                not closeout_summary["ready_for_api_database_write"]
                and not closeout_summary["ready_for_telegram_dispatch"]
                and not closeout_summary["ready_for_scheduler_attach"]
                and not closeout_summary["api_executes_cli"]
                and not closeout_summary["api_executes_llm"]
                and not closeout_summary["api_reads_approval_token"]
                and not closeout_summary["api_writes_file"]
                and not closeout_summary["api_writes_database"]
                and not closeout_summary["api_updates_review_state"]
                and not closeout_summary["summary_persistence_closeout_file_written"]
                and not closeout_summary["summary_persistence_record_written"]
                and not closeout_summary["metadata_patch_written"]
                and not closeout_summary["llm_call_executed"]
                and not closeout_summary["telegram_dispatched"]
                and not closeout_summary["database_connection_opened"]
                and not closeout_summary["database_write_executed"]
                and not closeout_summary["database_commit_executed"]
                and not closeout_summary["review_state_update_executed"]
                and not closeout_summary["scheduler_attached"]
            ),
        },
        {
            "key": "operator_confirmed_telegram_dispatch_gate",
            "label": "操作員確認本步只整理 Telegram dispatch gate，不實際派送",
            "passed": bool(
                operator[
                    "operator_confirmed_summary_persistence_telegram_dispatch_gate"
                ]
                and operator["operator_confirmed_telegram_message_reviewed"]
                and operator["operator_confirmed_dispatch_requires_manual_run_package"]
                and operator["operator_confirmed_no_api_telegram_dispatch"]
                and operator["operator_confirmed_no_llm_call"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "telegram_dispatch_gate_artifact_path_recorded",
            "label": "操作員需記錄 Telegram dispatch gate artifact 路徑",
            "passed": operator["telegram_dispatch_gate_artifact_path_recorded"],
        },
        {
            "key": "telegram_channel_label_recorded",
            "label": "dispatch gate 必須記錄人工確認的 Telegram channel label",
            "passed": operator["telegram_channel_label_recorded"],
        },
        {
            "key": "telegram_message_contract_safe",
            "label": "Telegram 訊息契約不可包含 token，且 API/scheduler 不派送",
            "passed": bool(
                message_contract["requires_evidence_refs"]
                and message_contract["requires_summary_payload_hash"]
                and not message_contract["api_dispatches_telegram"]
                and not message_contract["scheduler_dispatches_telegram"]
                and not message_contract["approval_tokens_allowed_in_message"]
            ),
        },
        {
            "key": "telegram_dispatch_gate_no_token_submitted_to_api",
            "label": "payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_gate_apply_real_write_not_requested_from_api",
            "label": "API/UI dispatch gate 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_gate(
    *,
    summary_persistence_closeout,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch gate 預覽；不執行副作用。"""
    closeout_summary = _closeout_summary(summary_persistence_closeout)
    operator = _operator_gate_summary(operator_evidence)
    message_contract = _dispatch_message_contract(closeout_summary, operator)
    gates = _gate_checks(
        closeout_summary,
        operator,
        message_contract,
        bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    gate_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_gate_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "prepare_ai_summary_telegram_dispatch_gate",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "telegram_dispatch_gate_reviewed": True,
        "telegram_dispatch_gate_passed": gate_passed,
        "summary_persistence_telegram_dispatch_gate_passed": gate_passed,
        "ready_for_next_manual_phase": gate_passed,
        "ready_for_summary_persistence_telegram_dispatch_run_package": gate_passed,
        "ready_for_manual_telegram_dispatch_run_package": gate_passed,
        "ready_for_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_llm_call": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_dispatches_telegram": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "telegram_dispatch_gate_file_written": False,
        "telegram_message_file_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": False,
        "telegram_dispatch_attempted": False,
        "review_state_update_executed": False,
        "read_only_query_executed": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "explicit_transaction_opened": False,
        "transaction_opened": False,
        "transaction_committed": False,
        "database_write_executed": False,
        "database_commit_executed": False,
        "database_rollback_executed": False,
        "external_network_executed": False,
        "scheduler_attached": False,
        "writes_executed": False,
        "would_write_database": False,
        "statement_count": closeout_summary["expected_dedupe_key_count"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "closeout_summary": closeout_summary,
        "operator_telegram_dispatch_gate_summary": operator,
        "telegram_message_contract": message_contract,
        "promotion_gate": {
            "allowed": gate_passed,
            "next_manual_phase": "summary_persistence_telegram_dispatch_run_package",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch gate artifact 與 closeout 摘要",
            "人工確認 Telegram message contract 只含 DB 實證與 evidence refs",
            "另開 Telegram dispatch run package / readiness / receipt gate 後才可派送",
            "若任何 gate 阻擋，停在 summary persistence closeout 階段",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_summary_persistence_telegram_dispatch_gate_api",
            "do_not_read_telegram_token_from_summary_persistence_telegram_dispatch_gate_api",
            "do_not_call_llm_from_summary_persistence_telegram_dispatch_gate",
            "do_not_dispatch_telegram_from_summary_persistence_telegram_dispatch_gate_api",
            "do_not_open_database_connection_from_summary_persistence_telegram_dispatch_gate",
            "do_not_write_metadata_json_from_summary_persistence_telegram_dispatch_gate",
            "do_not_update_review_state_from_summary_persistence_telegram_dispatch_gate",
            "do_not_write_dispatch_artifact_from_summary_persistence_telegram_dispatch_gate_api",
            "do_not_attach_scheduler_from_summary_persistence_telegram_dispatch_gate",
            "future_telegram_dispatch_must_use_run_package_readiness_receipt",
            "telegram_message_must_not_include_tokens",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
