"""候選審核 queue AI summary persistence operator run closeout preview。

本模組只在 metadata_json persistence receipt review 之後整理 closeout gate；
不回吐原始 receipt、不讀 approval token、不執行 CLI、不開 DB connection、不寫
metadata_json、不派送 Telegram、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
REQUIRED_RECEIPT_BOUNDARIES = {
    "do_not_execute_summary_persistence_writer_from_receipt_api",
    "do_not_read_approval_token_from_summary_persistence_receipt_api",
    "do_not_echo_operator_receipt_payload",
    "do_not_create_summary_persistence_receipt_artifact_from_api",
    "do_not_open_database_connection_from_summary_persistence_receipt",
    "do_not_write_metadata_json_from_summary_persistence_receipt",
    "do_not_update_review_state_from_summary_persistence_receipt",
    "do_not_commit_summary_persistence_receipt",
    "do_not_dispatch_telegram_from_summary_persistence_receipt",
    "do_not_attach_scheduler_from_summary_persistence_receipt",
}
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 _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(run_receipt):
    run_receipt = _as_dict(run_receipt)
    writer = _as_dict(run_receipt.get("writer_output_summary"))
    smoke = _as_dict(run_receipt.get("postwrite_smoke_summary"))
    expected_keys = _as_list(run_receipt.get("expected_dedupe_keys"))
    blocked_reasons = _as_list(run_receipt.get("blocked_reasons"))
    safe_boundaries = set(str(item) for item in _as_list(run_receipt.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_RECEIPT_BOUNDARIES - safe_boundaries)

    return {
        "provided": bool(run_receipt),
        "mode": run_receipt.get("mode"),
        "target_operation": run_receipt.get("target_operation"),
        "receipt_passed": bool(
            run_receipt.get("run_receipt_passed")
            or run_receipt.get("summary_persistence_run_receipt_passed")
        ),
        "ready_for_summary_persistence_closeout": bool(
            run_receipt.get("ready_for_summary_persistence_closeout")
        ),
        "ready_for_next_manual_phase": bool(
            run_receipt.get("ready_for_next_manual_phase")
        ),
        "expected_dedupe_key_count": len(expected_keys),
        "expected_summary_payload_hash": run_receipt.get(
            "expected_summary_payload_hash"
        ),
        "blocked_count": len(blocked_reasons),
        "writer_mode": writer.get("mode"),
        "writer_metadata_json_update_executed": bool(
            writer.get("metadata_json_update_executed")
        ),
        "writer_dedupe_keys_match_expected": bool(
            writer.get("dedupe_keys_match_expected")
        ),
        "writer_summary_hash_matches_expected": bool(
            writer.get("summary_payload_hash_matches_expected")
        ),
        "postwrite_smoke_passed": bool(smoke.get("postwrite_smoke_passed")),
        "postwrite_smoke_read_only": bool(smoke.get("read_only_query_executed")),
        "postwrite_smoke_metadata_json_verified": bool(
            smoke.get("metadata_json_update_verified")
        ),
        "postwrite_smoke_dedupe_keys_match_expected": bool(
            smoke.get("dedupe_keys_match_expected")
        ),
        "postwrite_smoke_summary_hash_matches_expected": bool(
            smoke.get("summary_payload_hash_matches_expected")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "ready_for_api_database_write": bool(
            run_receipt.get("ready_for_api_database_write")
        ),
        "ready_for_telegram_dispatch": bool(
            run_receipt.get("ready_for_telegram_dispatch")
        ),
        "ready_for_scheduler_attach": bool(run_receipt.get("ready_for_scheduler_attach")),
        "api_executes_cli": bool(run_receipt.get("api_executes_cli")),
        "api_executes_llm": bool(run_receipt.get("api_executes_llm")),
        "api_reads_approval_token": bool(run_receipt.get("api_reads_approval_token")),
        "api_writes_file": bool(run_receipt.get("api_writes_file")),
        "api_writes_database": bool(run_receipt.get("api_writes_database")),
        "api_updates_review_state": bool(run_receipt.get("api_updates_review_state")),
        "summary_persistence_record_written": bool(
            run_receipt.get("summary_persistence_record_written")
        ),
        "metadata_patch_written": bool(run_receipt.get("metadata_patch_written")),
        "llm_call_executed": bool(run_receipt.get("llm_call_executed")),
        "telegram_dispatched": bool(run_receipt.get("telegram_dispatched")),
        "database_connection_opened": bool(
            run_receipt.get("database_connection_opened")
        ),
        "database_write_executed": bool(run_receipt.get("database_write_executed")),
        "database_commit_executed": bool(run_receipt.get("database_commit_executed")),
        "review_state_update_executed": bool(
            run_receipt.get("review_state_update_executed")
        ),
        "scheduler_attached": bool(run_receipt.get("scheduler_attached")),
    }


def _operator_closeout_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "closeout_artifact_path_recorded": _has_text(
            operator_evidence.get("ai_summary_persistence_closeout_artifact_path")
            or operator_evidence.get("summary_persistence_closeout_artifact_path")
            or operator_evidence.get("closeout_artifact_path")
        ),
        "operator_confirmed_summary_persistence_closeout": bool(
            operator_evidence.get("operator_confirmed_summary_persistence_closeout")
            or operator_evidence.get("operator_confirmed_ai_summary_persistence_closeout")
        ),
        "operator_confirmed_telegram_dispatch_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_telegram_dispatch_requires_separate_gate"
            )
        ),
        "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")
        ),
        "operator_confirmed_no_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_telegram_dispatch")
        ),
        "closeout_notes_recorded": _has_text(operator_evidence.get("closeout_notes")),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _closeout_gates(receipt_summary, closeout_summary, apply_real_write):
    return [
        {
            "key": "receipt_preview_provided",
            "label": "必須提供上一階段 AI summary persistence receipt preview 摘要",
            "passed": bool(
                receipt_summary["provided"]
                and receipt_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_run_receipt_preview"
            ),
        },
        {
            "key": "receipt_target_operation_metadata_json",
            "label": "receipt 必須鎖定 metadata_json.ai_summary_review 持久化",
            "passed": bool(
                receipt_summary["target_operation"]
                == "persist_ai_summary_metadata_json"
            ),
        },
        {
            "key": "receipt_passed",
            "label": "receipt 必須已通過 writer output 與 post-write smoke 審核",
            "passed": receipt_summary["receipt_passed"],
        },
        {
            "key": "receipt_ready_for_summary_persistence_closeout",
            "label": "receipt 必須只放行到 summary persistence closeout",
            "passed": bool(
                receipt_summary["ready_for_summary_persistence_closeout"]
                and receipt_summary["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "receipt_expected_dedupe_keys_present",
            "label": "receipt 必須保有 run package dedupe key 摘要",
            "passed": bool(receipt_summary["expected_dedupe_key_count"]),
        },
        {
            "key": "writer_and_smoke_metadata_json_confirmed",
            "label": "writer output 與 smoke 必須確認 metadata_json.ai_summary_review 且 hash/key 一致",
            "passed": bool(
                receipt_summary["writer_metadata_json_update_executed"]
                and receipt_summary["writer_dedupe_keys_match_expected"]
                and receipt_summary["writer_summary_hash_matches_expected"]
                and receipt_summary["postwrite_smoke_read_only"]
                and receipt_summary["postwrite_smoke_passed"]
                and receipt_summary["postwrite_smoke_metadata_json_verified"]
                and receipt_summary["postwrite_smoke_dedupe_keys_match_expected"]
                and receipt_summary["postwrite_smoke_summary_hash_matches_expected"]
            ),
        },
        {
            "key": "receipt_safe_boundaries_complete",
            "label": "receipt 必須保留不讀 token、不執行 CLI、不寫 metadata_json 的安全邊界",
            "passed": receipt_summary["safe_boundaries_complete"],
        },
        {
            "key": "receipt_no_api_database_write",
            "label": "closeout 前不得出現 API/UI DB 寫入或 commit",
            "passed": bool(
                not receipt_summary["ready_for_api_database_write"]
                and not receipt_summary["api_writes_database"]
                and not receipt_summary["database_write_executed"]
                and not receipt_summary["database_commit_executed"]
            ),
        },
        {
            "key": "receipt_no_api_metadata_or_review_state_write",
            "label": "closeout 前不得由 API/UI 寫 metadata_json 或更新 review_state",
            "passed": bool(
                not receipt_summary["summary_persistence_record_written"]
                and not receipt_summary["metadata_patch_written"]
                and not receipt_summary["api_updates_review_state"]
                and not receipt_summary["review_state_update_executed"]
            ),
        },
        {
            "key": "receipt_no_scheduler_cli_llm_or_telegram",
            "label": "closeout 前不得從 API/UI 執行 CLI、LLM、Telegram 或掛 scheduler",
            "passed": bool(
                not receipt_summary["ready_for_telegram_dispatch"]
                and not receipt_summary["ready_for_scheduler_attach"]
                and not receipt_summary["api_executes_cli"]
                and not receipt_summary["api_executes_llm"]
                and not receipt_summary["llm_call_executed"]
                and not receipt_summary["telegram_dispatched"]
                and not receipt_summary["scheduler_attached"]
            ),
        },
        {
            "key": "receipt_no_token_or_file_side_effect",
            "label": "closeout 前 API/UI 不得讀 token 或寫 artifact 檔案",
            "passed": bool(
                not receipt_summary["api_reads_approval_token"]
                and not receipt_summary["api_writes_file"]
            ),
        },
        {
            "key": "closeout_artifact_path_recorded",
            "label": "操作員需記錄 summary persistence closeout artifact 路徑",
            "passed": closeout_summary["closeout_artifact_path_recorded"],
        },
        {
            "key": "operator_confirmed_summary_persistence_closeout",
            "label": "操作員確認 closeout 後才可進下一個 Telegram dispatch gate",
            "passed": closeout_summary[
                "operator_confirmed_summary_persistence_closeout"
            ],
        },
        {
            "key": "operator_confirmed_telegram_dispatch_requires_separate_gate",
            "label": "操作員確認 Telegram dispatch 必須另開 gate，不由 closeout 發送",
            "passed": closeout_summary[
                "operator_confirmed_telegram_dispatch_requires_separate_gate"
            ],
        },
        {
            "key": "operator_confirmed_no_scheduler_attach",
            "label": "操作員確認本階段不掛 scheduler",
            "passed": closeout_summary["operator_confirmed_no_scheduler_attach"],
        },
        {
            "key": "operator_confirmed_no_api_db_write",
            "label": "操作員確認本階段不由 API/UI 寫 DB",
            "passed": closeout_summary["operator_confirmed_no_api_db_write"],
        },
        {
            "key": "operator_confirmed_no_telegram_dispatch",
            "label": "操作員確認本階段不派送 Telegram",
            "passed": closeout_summary["operator_confirmed_no_telegram_dispatch"],
        },
        {
            "key": "closeout_no_approval_token_submitted_to_api",
            "label": "closeout payload 不得包含一次性 approval token key",
            "passed": not closeout_summary["approval_token_submitted_to_api"],
        },
        {
            "key": "closeout_apply_real_write_not_requested_from_api",
            "label": "API/UI closeout 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_run_closeout(
    *,
    run_receipt,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 AI summary persistence CLI 寫入後 closeout gate；不執行副作用。"""
    receipt_summary = _receipt_summary(run_receipt)
    closeout_summary = _operator_closeout_summary(operator_evidence)
    gates = _closeout_gates(
        receipt_summary,
        closeout_summary,
        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_run_closeout_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "persist_ai_summary_metadata_json",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "closeout_reviewed": True,
        "closeout_passed": closeout_passed,
        "summary_persistence_closeout_passed": closeout_passed,
        "ready_for_next_manual_phase": closeout_passed,
        "ready_for_summary_persistence_telegram_dispatch_gate": closeout_passed,
        "ready_for_summary_persistence_cli_run": False,
        "ready_for_real_write": False,
        "ready_for_api_database_write": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_scheduler_attach": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "summary_persistence_closeout_file_written": False,
        "closeout_file_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "transaction_file_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": 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": receipt_summary["expected_dedupe_key_count"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "receipt_summary": receipt_summary,
        "operator_closeout_summary": closeout_summary,
        "promotion_gate": {
            "allowed": closeout_passed,
            "next_manual_phase": "summary_persistence_telegram_dispatch_gate",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "telegram_dispatch_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 summary persistence closeout artifact 與 receipt 摘要",
            "人工確認 metadata_json.ai_summary_review 已可供後續摘要派送 gate 使用",
            "另開 Telegram dispatch preflight / run package / receipt gate 後才允許派送",
            "若任何 closeout gate 阻擋，停在 receipt 階段並保留 feature flags 關閉",
        ],
        "safe_boundaries": [
            "do_not_echo_operator_receipt_payload",
            "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",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
