"""候選審核 queue AI summary Telegram dispatch report closeout preview。

本模組只在 report run receipt 通過後整理 report closeout gate；不讀 approval
或 Telegram token、不呼叫 LLM、不產報表、不派送 Telegram、不開 DB、不寫檔、
不更新 review_state、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-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"
REQUIRED_RECEIPT_BOUNDARIES = {
    "do_not_read_approval_token_from_report_run_receipt_api",
    "do_not_read_telegram_token_from_report_run_receipt_api",
    "do_not_call_llm_from_report_run_receipt",
    "do_not_generate_report_from_report_run_receipt_api",
    "do_not_write_report_artifact_from_report_run_receipt_api",
    "do_not_dispatch_telegram_from_report_run_receipt_api",
    "do_not_open_database_connection_from_report_run_receipt",
    "do_not_update_review_state_from_report_run_receipt",
    "do_not_attach_scheduler_from_report_run_receipt",
}
TARGET_TABLE = "market_alert_review_queue"
TARGET_COLUMN = "metadata_json"
SUMMARY_METADATA_KEY = "ai_summary_review"
FALSE_RESPONSE_KEYS = (
    "ready_for_report_generation",
    "ready_for_manual_report_generation",
    "ready_for_ai_summary_generation",
    "ready_for_llm_call",
    "ready_for_telegram_dispatch",
    "ready_for_manual_telegram_dispatch",
    "ready_for_api_database_write",
    "ready_for_scheduler_attach",
    "ready_for_real_write",
    "api_executes_cli",
    "api_executes_llm",
    "api_dispatches_telegram",
    "api_reads_approval_token",
    "api_writes_file",
    "api_writes_database",
    "api_updates_review_state",
    "telegram_dispatch_report_closeout_file_written",
    "report_closeout_file_written",
    "closeout_file_written",
    "report_run_receipt_file_written",
    "report_receipt_file_written",
    "report_output_file_written",
    "report_file_written",
    "report_record_written",
    "report_manifest_written",
    "archive_file_written",
    "archive_record_written",
    "archive_manifest_written",
    "summary_file_written",
    "summary_record_written",
    "summary_manifest_written",
    "summary_persistence_record_written",
    "metadata_patch_written",
    "ai_summary_generated",
    "llm_call_executed",
    "ollama_call_executed",
    "gemini_call_executed",
    "telegram_dispatched",
    "telegram_dispatch_attempted",
    "review_state_update_executed",
    "read_only_query_executed",
    "database_connection_opened",
    "database_session_created",
    "explicit_transaction_opened",
    "transaction_opened",
    "transaction_committed",
    "database_write_executed",
    "database_commit_executed",
    "database_rollback_executed",
    "external_network_executed",
    "scheduler_attached",
    "writes_executed",
    "would_write_database",
)


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 _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


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


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


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 _receipt_summary(report_run_receipt):
    receipt_payload = _as_dict(report_run_receipt)
    report_receipt = _as_dict(
        receipt_payload.get("telegram_dispatch_report_run_receipt_summary")
    )
    readiness = _as_dict(
        receipt_payload.get("telegram_dispatch_report_run_readiness_summary")
    )
    safe_boundaries = set(
        str(item) for item in _as_list(receipt_payload.get("safe_boundaries"))
    )
    missing_boundaries = sorted(REQUIRED_RECEIPT_BOUNDARIES - safe_boundaries)

    return {
        "provided": bool(receipt_payload),
        "mode": receipt_payload.get("mode"),
        "target_operation": receipt_payload.get("target_operation"),
        "receipt_passed": bool(
            receipt_payload.get("telegram_dispatch_report_run_receipt_passed")
            or receipt_payload.get(
                "summary_persistence_telegram_dispatch_report_run_receipt_passed"
            )
            or receipt_payload.get("report_run_receipt_passed")
        ),
        "ready_for_market_intel_report_closeout": bool(
            receipt_payload.get("ready_for_market_intel_report_closeout")
        ),
        "ready_for_next_manual_phase": bool(
            receipt_payload.get("ready_for_next_manual_phase")
        ),
        "statement_count": _safe_int(receipt_payload.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            receipt_payload.get("expected_summary_payload_hash")
            or report_receipt.get("expected_summary_payload_hash"),
            80,
        ),
        "readiness_mode": readiness.get("mode"),
        "readiness_ready": bool(
            readiness.get("telegram_dispatch_report_run_readiness_ready")
            and readiness.get("ready_for_market_intel_report_run_receipt")
        ),
        "readiness_manifest_version": readiness.get("manifest_version"),
        "target_report_family": report_receipt.get("target_report_family"),
        "language": report_receipt.get("language"),
        "report_receipt_provided": bool(report_receipt.get("provided")),
        "report_receipt_mode": report_receipt.get("mode"),
        "report_generated": bool(report_receipt.get("report_generated")),
        "report_output_artifact_path": report_receipt.get(
            "report_output_artifact_path"
        ),
        "report_output_hash": report_receipt.get("report_output_hash"),
        "summary_payload_hash": report_receipt.get("summary_payload_hash"),
        "summary_payload_hash_matches_expected": bool(
            report_receipt.get("summary_payload_hash_matches_expected")
        ),
        "required_report_sections_present": bool(
            report_receipt.get("required_report_sections_present")
        ),
        "section_keys": _as_list(report_receipt.get("section_keys")),
        "approval_or_telegram_token_key_detected": bool(
            report_receipt.get("approval_or_telegram_token_key_detected")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "blocked_count": len(_as_list(receipt_payload.get("blocked_reasons"))),
        **{key: bool(receipt_payload.get(key)) for key in FALSE_RESPONSE_KEYS},
    }


def _operator_closeout_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "report_closeout_artifact_path_recorded": _has_text(
            operator_evidence.get("report_closeout_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_closeout_artifact_path"
            )
            or operator_evidence.get("market_intel_report_closeout_artifact_path")
        ),
        "report_run_receipt_artifact_path_recorded": _has_text(
            operator_evidence.get("report_run_receipt_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_run_receipt_artifact_path"
            )
        ),
        "report_output_artifact_path_recorded": _has_text(
            operator_evidence.get("report_output_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_output_artifact_path")
        ),
        "operator_confirmed_report_closeout": bool(
            operator_evidence.get("operator_confirmed_report_closeout")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_closeout"
            )
        ),
        "operator_confirmed_report_receipt_archived": bool(
            operator_evidence.get("operator_confirmed_report_receipt_archived")
            or operator_evidence.get("operator_confirmed_receipt_archived")
        ),
        "operator_confirmed_report_output_hash_matched": bool(
            operator_evidence.get("operator_confirmed_report_output_hash_matched")
            or operator_evidence.get("operator_confirmed_summary_hash_matched")
        ),
        "operator_confirmed_report_sections_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_sections_reviewed")
        ),
        "operator_confirmed_report_archive_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_archive_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_closeout": bool(
            operator_evidence.get("operator_confirmed_no_token_in_report_closeout")
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "operator_confirmed_no_api_report_generation": bool(
            operator_evidence.get("operator_confirmed_no_api_report_generation")
            or operator_evidence.get("operator_confirmed_no_api_report_write")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "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")
        ),
        "closeout_notes_recorded": _has_text(
            operator_evidence.get("report_closeout_notes")
            or operator_evidence.get("closeout_notes")
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _closeout_gates(receipt, operator, apply_real_write):
    return [
        {
            "key": "report_run_receipt_preview_provided",
            "label": "必須提供上一階段 report run receipt preview",
            "passed": bool(
                receipt["provided"]
                and receipt["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_run_receipt_preview"
            ),
        },
        {
            "key": "report_run_receipt_passed",
            "label": "report run receipt 必須已通過",
            "passed": receipt["receipt_passed"],
        },
        {
            "key": "report_run_receipt_ready_for_closeout",
            "label": "report run receipt 必須只放行到 report closeout",
            "passed": bool(
                receipt["ready_for_market_intel_report_closeout"]
                and receipt["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "report_run_receipt_artifact_verified",
            "label": "receipt 必須有 report artifact path/hash、章節與 summary hash",
            "passed": bool(
                receipt["report_receipt_provided"]
                and receipt["report_generated"]
                and receipt["report_output_artifact_path"]
                and receipt["report_output_hash"]
                and receipt["summary_payload_hash_matches_expected"]
                and receipt["required_report_sections_present"]
            ),
        },
        {
            "key": "report_run_receipt_runtime_boundaries_clear",
            "label": "receipt 不得顯示 API 產報表、DB、Telegram、LLM、scheduler 或檔案副作用",
            "passed": bool(
                not receipt["ready_for_report_generation"]
                and not receipt["ready_for_api_database_write"]
                and not receipt["ready_for_telegram_dispatch"]
                and not receipt["ready_for_scheduler_attach"]
                and not receipt["api_executes_cli"]
                and not receipt["api_executes_llm"]
                and not receipt["api_dispatches_telegram"]
                and not receipt["api_reads_approval_token"]
                and not receipt["api_writes_file"]
                and not receipt["api_writes_database"]
                and not receipt["api_updates_review_state"]
                and not receipt["report_file_written"]
                and not receipt["report_record_written"]
                and not receipt["report_manifest_written"]
                and not receipt["ai_summary_generated"]
                and not receipt["llm_call_executed"]
                and not receipt["telegram_dispatched"]
                and not receipt["telegram_dispatch_attempted"]
                and not receipt["database_connection_opened"]
                and not receipt["database_write_executed"]
                and not receipt["database_commit_executed"]
                and not receipt["review_state_update_executed"]
                and not receipt["scheduler_attached"]
            ),
        },
        {
            "key": "report_run_receipt_safe_boundaries_complete",
            "label": "receipt 必須保留 report/token/DB/scheduler 安全邊界",
            "passed": receipt["safe_boundaries_complete"],
        },
        {
            "key": "report_run_receipt_no_token_key",
            "label": "receipt 不得包含 approval 或 Telegram token key",
            "passed": not receipt["approval_or_telegram_token_key_detected"],
        },
        {
            "key": "report_closeout_artifacts_recorded",
            "label": "操作員需記錄 closeout、receipt 與 report output artifact path",
            "passed": bool(
                operator["report_closeout_artifact_path_recorded"]
                and operator["report_run_receipt_artifact_path_recorded"]
                and operator["report_output_artifact_path_recorded"]
            ),
        },
        {
            "key": "operator_confirmed_report_closeout",
            "label": "操作員確認 report closeout、receipt 封存、hash 與章節",
            "passed": bool(
                operator["operator_confirmed_report_closeout"]
                and operator["operator_confirmed_report_receipt_archived"]
                and operator["operator_confirmed_report_output_hash_matched"]
                and operator["operator_confirmed_report_sections_reviewed"]
            ),
        },
        {
            "key": "operator_confirmed_report_archive_requires_separate_gate",
            "label": "操作員確認後續 report archive 必須另開 gate",
            "passed": operator[
                "operator_confirmed_report_archive_requires_separate_gate"
            ],
        },
        {
            "key": "operator_confirmed_report_closeout_runtime_boundaries",
            "label": "操作員確認本階段不產報表、不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_closeout"]
                and operator["operator_confirmed_no_api_report_generation"]
                and operator["operator_confirmed_no_api_telegram_dispatch"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_llm_call"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "report_closeout_no_token_submitted_to_api",
            "label": "closeout payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_closeout_apply_real_write_not_requested_from_api",
            "label": "API/UI report closeout 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_closeout(
    *,
    telegram_dispatch_report_run_receipt,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report closeout gate；不執行任何副作用。"""
    receipt = _receipt_summary(telegram_dispatch_report_run_receipt)
    operator = _operator_closeout_summary(operator_evidence)
    gates = _closeout_gates(receipt, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    closeout_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_closeout_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            SUMMARY_METADATA_KEY,
            "telegram_dispatch_report_closeout",
        ],
        "target_operation": "closeout_manual_market_intel_report",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_closeout_reviewed": True,
        "telegram_dispatch_report_closeout_passed": closeout_passed,
        "summary_persistence_telegram_dispatch_report_closeout_passed": closeout_passed,
        "report_closeout_passed": closeout_passed,
        "ready_for_next_manual_phase": closeout_passed,
        "ready_for_market_intel_report_archive": closeout_passed,
        **{key: False for key in FALSE_RESPONSE_KEYS},
        "statement_count": receipt["statement_count"],
        "expected_summary_payload_hash": receipt["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_run_receipt_summary": receipt,
        "operator_telegram_dispatch_report_closeout": operator,
        "promotion_gate": {
            "allowed": closeout_passed,
            "next_manual_phase": "market_intel_report_archive",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_generate_report": True,
            "api_must_not_dispatch_telegram": True,
            "report_archive_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report closeout artifact path",
            "確認 report receipt、report output artifact、hash 與章節都已封存",
            "下一階段 report archive 才整理長期封存；本 API 不寫檔、不補產報表",
            "若任何 closeout gate 阻擋，停在 receipt 階段並保留 feature flags 關閉",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_closeout_api",
            "do_not_read_telegram_token_from_report_closeout_api",
            "do_not_call_llm_from_report_closeout",
            "do_not_generate_report_from_report_closeout_api",
            "do_not_write_report_artifact_from_report_closeout_api",
            "do_not_dispatch_telegram_from_report_closeout_api",
            "do_not_open_database_connection_from_report_closeout",
            "do_not_update_review_state_from_report_closeout",
            "do_not_attach_scheduler_from_report_closeout",
            "future_market_intel_report_archive_must_use_separate_gate",
            "report_closeout_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
