"""候選審核 queue AI summary Telegram dispatch run readiness preview。

本模組只檢查人工 Telegram 派送前的 readiness 證據；不讀 approval 或
Telegram token、不呼叫 LLM、不派送 Telegram、不開 DB、不寫檔、不更新
review_state、不 commit、不掛 scheduler。
"""

import hashlib
import json


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-token",
    "bot_token",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
    "telegram_token_present",
    "telegram_token_configured",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
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 _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _stable_hash(value):
    encoded = json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


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 _side_effects_clear(payload):
    blocked_keys = (
        "ready_for_api_database_write",
        "ready_for_telegram_dispatch",
        "ready_for_scheduler_attach",
        "ready_for_llm_call",
        "api_executes_cli",
        "api_executes_llm",
        "api_dispatches_telegram",
        "api_reads_approval_token",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "package_artifact_created",
        "telegram_dispatch_gate_file_written",
        "telegram_dispatch_run_package_file_written",
        "telegram_dispatch_run_readiness_file_written",
        "telegram_message_file_written",
        "summary_file_written",
        "summary_record_written",
        "summary_persistence_record_written",
        "metadata_patch_written",
        "database_connection_opened",
        "database_session_created",
        "explicit_transaction_opened",
        "transaction_opened",
        "transaction_committed",
        "database_write_executed",
        "database_commit_executed",
        "database_rollback_executed",
        "review_state_update_executed",
        "llm_call_executed",
        "ollama_call_executed",
        "gemini_call_executed",
        "telegram_dispatched",
        "telegram_dispatch_attempted",
        "external_network_executed",
        "scheduler_attached",
        "writes_executed",
        "would_write_database",
    )
    payload = _as_dict(payload)
    return all(not payload.get(key) for key in blocked_keys)


def _package_summary(run_package):
    run_package = _as_dict(run_package)
    manifest = _as_dict(run_package.get("message_package_manifest"))
    commands = [_as_dict(item) for item in _as_list(run_package.get("command_bundle"))]
    artifacts = [_as_dict(item) for item in _as_list(run_package.get("required_artifacts"))]
    manual_dispatch_commands = [
        command
        for command in commands
        if command.get("key") == "manual_telegram_dispatch"
        and command.get("executes_telegram") is True
    ]
    receipt_commands = [
        command for command in commands if command.get("key") == "dispatch_receipt"
    ]
    return {
        "provided": bool(run_package),
        "mode": run_package.get("mode"),
        "package_ready": bool(
            run_package.get("telegram_dispatch_run_package_ready")
            or run_package.get("package_ready")
        ),
        "ready_for_summary_persistence_telegram_dispatch_run_readiness": bool(
            run_package.get(
                "ready_for_summary_persistence_telegram_dispatch_run_readiness"
            )
        ),
        "ready_for_next_manual_phase": bool(run_package.get("ready_for_next_manual_phase")),
        "target_operation": run_package.get("target_operation"),
        "target_channel": manifest.get("target_channel"),
        "message_format": manifest.get("message_format"),
        "manifest_hash": manifest.get("manifest_hash") or _stable_hash(manifest),
        "expected_dedupe_key_count": _safe_int(
            manifest.get("expected_dedupe_key_count")
            or run_package.get("statement_count")
        ),
        "expected_summary_payload_hash": manifest.get("expected_summary_payload_hash"),
        "requires_evidence_refs": bool(manifest.get("requires_evidence_refs")),
        "requires_summary_payload_hash": bool(
            manifest.get("requires_summary_payload_hash")
        ),
        "api_dispatches_telegram": bool(
            manifest.get("api_dispatches_telegram")
            or run_package.get("api_dispatches_telegram")
        ),
        "scheduler_dispatches_telegram": bool(
            manifest.get("scheduler_dispatches_telegram")
        ),
        "approval_tokens_allowed_in_message": bool(
            manifest.get("approval_tokens_allowed_in_message")
        ),
        "command_count": len(commands),
        "manual_dispatch_command_present": bool(manual_dispatch_commands),
        "manual_dispatch_command_executed": any(
            command.get("executed") for command in manual_dispatch_commands
        ),
        "dispatch_receipt_command_present": bool(receipt_commands),
        "commands_executed": any(command.get("executed") for command in commands),
        "required_artifact_count": len(artifacts),
        "required_artifact_keys": [item.get("key") for item in artifacts],
        "side_effects_clear": _side_effects_clear(run_package),
        "blocked_reasons": _as_list(run_package.get("blocked_reasons")),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    artifact_paths = {
        "telegram_dispatch_gate_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_telegram_dispatch_gate_artifact_path")
            or operator_evidence.get("telegram_dispatch_gate_artifact_path")
        ),
        "telegram_dispatch_run_package_artifact_path": _safe_text(
            operator_evidence.get(
                "ai_summary_telegram_dispatch_run_package_artifact_path"
            )
            or operator_evidence.get("telegram_dispatch_run_package_artifact_path")
        ),
        "telegram_message_preview_artifact_path": _safe_text(
            operator_evidence.get("telegram_message_preview_artifact_path")
            or operator_evidence.get("ai_summary_telegram_message_preview_artifact_path")
        ),
        "telegram_dispatch_receipt_artifact_path": _safe_text(
            operator_evidence.get("telegram_dispatch_receipt_artifact_path")
            or operator_evidence.get("ai_summary_telegram_dispatch_receipt_artifact_path")
        ),
    }
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        **artifact_paths,
        "artifact_path_count": sum(
            1 for value in artifact_paths.values() if _has_text(value)
        ),
        "telegram_channel_label": _safe_text(
            operator_evidence.get("telegram_channel_label")
            or operator_evidence.get("telegram_dispatch_channel")
            or operator_evidence.get("notification_channel")
        ),
        "operator_confirmed_ai_summary_telegram_dispatch_run_readiness": bool(
            operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_run_readiness"
            )
            or operator_evidence.get("operator_confirmed_telegram_dispatch_run_readiness")
        ),
        "operator_confirmed_run_package_artifact_reviewed": bool(
            operator_evidence.get("operator_confirmed_run_package_artifact_reviewed")
            or operator_evidence.get(
                "operator_confirmed_telegram_dispatch_run_package_reviewed"
            )
        ),
        "operator_confirmed_message_preview_reviewed": bool(
            operator_evidence.get("operator_confirmed_message_preview_reviewed")
            or operator_evidence.get("operator_confirmed_telegram_message_reviewed")
        ),
        "operator_confirmed_manual_dispatch_command_reviewed": bool(
            operator_evidence.get("operator_confirmed_manual_dispatch_command_reviewed")
            or operator_evidence.get("operator_confirmed_command_bundle_reviewed")
        ),
        "operator_confirmed_telegram_token_shell_only": bool(
            operator_evidence.get("operator_confirmed_telegram_token_shell_only")
            or operator_evidence.get("operator_acknowledged_telegram_token_shell_only")
        ),
        "operator_confirmed_no_token_in_artifacts": bool(
            operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "operator_confirmed_dispatch_receipt_required": bool(
            operator_evidence.get("operator_confirmed_dispatch_receipt_required")
        ),
        "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_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _readiness_gates(*, package, operator, apply_real_write):
    return [
        {
            "key": "telegram_dispatch_run_package_ready",
            "label": "Telegram dispatch run package 必須已通過並放行到 run readiness",
            "passed": bool(
                package["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_package_preview"
                and package["package_ready"]
                and package[
                    "ready_for_summary_persistence_telegram_dispatch_run_readiness"
                ]
                and package["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "telegram_dispatch_message_manifest_ready",
            "label": "message manifest 必須保有 channel、format、evidence refs 與 summary hash",
            "passed": bool(
                package["target_channel"]
                and package["message_format"] == "market_intel_ai_summary_brief"
                and package["requires_evidence_refs"]
                and package["requires_summary_payload_hash"]
                and package["expected_summary_payload_hash"]
                and package["expected_dedupe_key_count"] > 0
                and not package["api_dispatches_telegram"]
                and not package["scheduler_dispatches_telegram"]
                and not package["approval_tokens_allowed_in_message"]
            ),
        },
        {
            "key": "telegram_dispatch_command_bundle_ready",
            "label": "run package 必須含 manual dispatch 與 receipt 步驟，且 API 尚未執行命令",
            "passed": bool(
                package["command_count"] >= 5
                and package["manual_dispatch_command_present"]
                and package["dispatch_receipt_command_present"]
                and not package["manual_dispatch_command_executed"]
                and not package["commands_executed"]
            ),
        },
        {
            "key": "telegram_dispatch_readiness_artifacts_recorded",
            "label": "dispatch gate、run package、message preview 與 receipt artifact path 必須齊備",
            "passed": bool(
                operator["telegram_dispatch_gate_artifact_path"]
                and operator["telegram_dispatch_run_package_artifact_path"]
                and operator["telegram_message_preview_artifact_path"]
                and operator["telegram_dispatch_receipt_artifact_path"]
            ),
        },
        {
            "key": "operator_confirmed_telegram_dispatch_run_readiness",
            "label": "操作員確認 token shell-only、message preview、manual command、receipt 與 no-side-effect 邊界",
            "passed": bool(
                operator[
                    "operator_confirmed_ai_summary_telegram_dispatch_run_readiness"
                ]
                and operator["operator_confirmed_run_package_artifact_reviewed"]
                and operator["operator_confirmed_message_preview_reviewed"]
                and operator["operator_confirmed_manual_dispatch_command_reviewed"]
                and operator["operator_confirmed_telegram_token_shell_only"]
                and operator["operator_confirmed_no_token_in_artifacts"]
                and operator["operator_confirmed_dispatch_receipt_required"]
                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_run_readiness_no_token_submitted_to_api",
            "label": "payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_run_readiness_apply_real_write_not_requested_from_api",
            "label": "API/UI run readiness 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
        {
            "key": "telegram_dispatch_run_package_has_no_side_effects",
            "label": "run package 不得已有 DB、檔案、LLM、Telegram 或 scheduler 副作用",
            "passed": package["side_effects_clear"],
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_readiness(
    *,
    telegram_dispatch_run_package,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch operator readiness preview；不執行派送或副作用。"""
    package = _package_summary(telegram_dispatch_run_package)
    operator = _operator_summary(operator_evidence)
    gates = _readiness_gates(
        package=package,
        operator=operator,
        apply_real_write=bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    readiness_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_readiness_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "manual_ai_summary_telegram_dispatch_readiness",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "run_readiness_ready": readiness_ready,
        "telegram_dispatch_run_readiness_ready": readiness_ready,
        "summary_persistence_telegram_dispatch_run_readiness_ready": readiness_ready,
        "ready_for_next_manual_phase": readiness_ready,
        "ready_for_manual_telegram_dispatch": readiness_ready,
        "ready_for_summary_persistence_telegram_dispatch_run_receipt": readiness_ready,
        "ready_for_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_llm_call": False,
        "ready_for_real_write": 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,
        "package_artifact_created": False,
        "telegram_dispatch_run_readiness_file_written": False,
        "run_readiness_file_written": False,
        "telegram_dispatch_run_package_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": package["expected_dedupe_key_count"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_run_package_summary": package,
        "operator_telegram_dispatch_run_readiness": operator,
        "manual_dispatch_boundary": {
            "api_may_dispatch_telegram": False,
            "operator_shell_required": True,
            "telegram_token_shell_only": True,
            "requires_message_preview_review": True,
            "requires_dispatch_receipt": True,
            "requires_receipt_review_after_dispatch": True,
        },
        "promotion_gate": {
            "allowed": readiness_ready,
            "next_manual_phase": "summary_persistence_telegram_dispatch_run_receipt",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "在 shell 中以 TELEGRAM_BOT_TOKEN 提供一次性派送權限，不把 token 貼回 UI/API",
            "人工執行 message preview 對應的 Telegram dispatch command",
            "保存 Telegram API response、message id、channel 與 summary payload hash 到 dispatch receipt",
            "將 dispatch receipt 回貼到下一階段 receipt review；API 不補發、不重送、不掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_run_readiness_api",
            "do_not_read_telegram_token_from_telegram_dispatch_run_readiness_api",
            "do_not_call_llm_from_telegram_dispatch_run_readiness",
            "do_not_dispatch_telegram_from_telegram_dispatch_run_readiness_api",
            "do_not_open_database_connection_from_telegram_dispatch_run_readiness",
            "do_not_write_dispatch_artifact_from_telegram_dispatch_run_readiness_api",
            "do_not_update_review_state_from_telegram_dispatch_run_readiness",
            "do_not_attach_scheduler_from_telegram_dispatch_run_readiness",
            "telegram_token_shell_only_for_manual_dispatch",
            "future_telegram_dispatch_result_must_use_receipt_closeout",
            "telegram_message_must_not_include_tokens",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
