"""市場情報 MCP fetch candidate queue writer run closeout review preview。

本模組只審核 operator shell writer run receipt review 之後的 closeout 摘要；
API/UI 不讀 receipt 原文、不讀 approval token、不執行 CLI、不開 DB、不寫 queue、
不做 post-closeout query、不掛 scheduler。
"""

from copy import deepcopy

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE
from services.market_intel.mcp_fetch_candidate_queue_writer_run_readiness import (
    ARTIFACT_PREFIX,
    BACKUP_PREFIX,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_run_receipt_review import (
    build_mcp_fetch_candidate_queue_writer_run_receipt_review_preview,
)


_SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE = None

FORBIDDEN_SECRET_KEYS = (
    "approval_token",
    "approval-token",
    "api_key",
    "authorization",
    "bearer",
    "client_secret",
    "cookie",
    "password",
    "secret",
    "session_cookie",
    "token",
)

SAFE_SECRET_METADATA_KEYS = {
    "no_approval_token_payload",
    "operator_confirmed_no_approval_token_payload",
    "token_not_logged",
}

_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_execution",
    "allow_cli_execution",
    "allow_database_write",
    "allow_external_network_in_api",
    "allow_scheduler_attach",
    "api_execution_allowed",
    "api_executed_cli",
    "api_executes",
    "api_executes_cli",
    "api_opens_database_connection",
    "api_reads_approval_token",
    "api_uses_external_network",
    "api_writes_database",
    "api_writes_file",
    "apply_real_write",
    "attach_scheduler",
    "candidate_queue_created_by_api",
    "candidate_queue_persisted_by_api",
    "candidate_review_state_updated",
    "cli_executed_by_api",
    "closeout_file_written",
    "closeout_persisted",
    "command_executed_by_api",
    "database_commit_executed",
    "database_connection_opened",
    "database_session_created",
    "database_write_executed_by_api",
    "execute_requested",
    "external_network_executed_by_api",
    "file_written",
    "network_request_allowed",
    "opens_database_connection",
    "package_artifact_created",
    "payload_persisted",
    "post_closeout_query_executed_by_api",
    "ready_for_api_database_write",
    "ready_for_real_write",
    "real_write_allowed_by_api",
    "review_state_update_executed",
    "run_closeout_file_written",
    "run_closeout_persisted",
    "scheduler_attach",
    "scheduler_attached",
    "write_database",
    "writes_database",
    "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=500):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _safe_path(value, *, prefixes, suffixes):
    if not isinstance(value, str):
        return False
    normalized = value.strip().replace("\\", "/")
    if not normalized or normalized.startswith("/"):
        return False
    parts = [part for part in normalized.split("/") if part]
    if any(part in (".", "..") for part in parts):
        return False
    return normalized.startswith(prefixes) and normalized.endswith(suffixes)


def _contains_forbidden_key(value, forbidden_keys, *, safe_keys=None):
    safe_keys = safe_keys or set()
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in safe_keys and isinstance(nested, bool):
                continue
            if any(forbidden_key in normalized_key for forbidden_key in forbidden_keys):
                return True
            if _contains_forbidden_key(nested, forbidden_keys, safe_keys=safe_keys):
                return True
    elif isinstance(value, list):
        return any(
            _contains_forbidden_key(item, forbidden_keys, safe_keys=safe_keys)
            for item in value
        )
    return False


def _blocked_side_effects(payload):
    found = []

    def visit(value, path):
        if isinstance(value, dict):
            for key, item in value.items():
                normalized_key = str(key).lower()
                key_path = f"{path}.{key}" if path else key
                if normalized_key in _BLOCKED_SIDE_EFFECT_KEYS and bool(item):
                    found.append(key_path)
                visit(item, key_path)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                visit(item, f"{path}[{index}]")

    visit(payload, "")
    return found


def _receipt_review_from_inputs(receipt_package, receipt_result, phase):
    if isinstance(receipt_result, dict) and receipt_result:
        return receipt_result

    receipt_package = _as_dict(receipt_package)
    return build_mcp_fetch_candidate_queue_writer_run_receipt_review_preview(
        writer_run_readiness_package=(
            receipt_package.get("writer_run_readiness_package")
            or receipt_package.get("candidate_queue_writer_run_readiness")
            or receipt_package.get("writer_run_readiness")
            or receipt_package.get("run_readiness_package")
            or {}
        ),
        writer_run_readiness_result=(
            receipt_package.get("writer_run_readiness_result")
            or receipt_package.get("mcp_fetch_candidate_queue_writer_run_readiness")
        ),
        writer_run_receipt=(
            receipt_package.get("writer_run_receipt")
            or receipt_package.get("candidate_queue_writer_run_receipt")
            or receipt_package.get("run_receipt")
            or receipt_package.get("receipt_payload")
            or receipt_package.get("receipt")
        ),
        phase=phase,
    )


def _sample_run_closeout_review_package():
    global _SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE
    if _SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE is not None:
        return deepcopy(_SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE)

    run_package_id = "market-intel-candidate-writer-run-package-sample"
    receipt_id = "market-intel-candidate-writer-run-receipt-sample"
    payload_row_count = 2
    writer_output_path = (
        ARTIFACT_PREFIX + "candidate-queue-writer-output-sample.json"
    )
    postwrite_smoke_result_path = (
        ARTIFACT_PREFIX + "candidate-queue-writer-postwrite-smoke-sample.json"
    )
    backup_artifact_path = BACKUP_PREFIX + "momo_pro_system_backup_sample.zip"
    receipt_package = {
        "writer_run_readiness_package": {
            "writer_run_package_review_package": {
                "run_package_id": run_package_id,
                "target_table": TARGET_TABLE,
            }
        },
        "writer_run_readiness_result": {
            "mode": "mcp_fetch_candidate_queue_writer_run_readiness_review",
            "mcp_fetch_candidate_queue_writer_run_readiness_accepted": True,
            "ready_for_candidate_queue_writer_run_receipt_review": True,
            "payload_row_count": payload_row_count,
            "network_request_allowed": False,
            "api_executes_cli": False,
            "api_reads_approval_token": False,
            "api_opens_database_connection": False,
            "api_writes_database": False,
            "api_writes_file": False,
            "api_uses_external_network": False,
            "database_write_executed": False,
            "cli_executed": False,
            "file_written": False,
            "scheduler_attached": False,
            "candidate_queue_created": False,
            "candidate_queue_persisted": False,
        },
        "writer_run_receipt": {
            "receipt_id": receipt_id,
            "run_package_id": run_package_id,
            "target_table": TARGET_TABLE,
            "payload_row_count": payload_row_count,
            "writer_output_path": writer_output_path,
            "postwrite_smoke_result_path": postwrite_smoke_result_path,
            "backup_artifact_path": backup_artifact_path,
        },
    }
    receipt_result = {
        "mode": "mcp_fetch_candidate_queue_writer_run_receipt_review",
        "mcp_fetch_candidate_queue_writer_run_receipt_review_accepted": True,
        "ready_for_candidate_queue_writer_run_closeout_review": True,
        "payload_row_count": payload_row_count,
        "blocked_reasons": [],
        "network_request_allowed": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_uses_external_network": False,
        "postwrite_query_executed_by_api": False,
        "database_write_executed": False,
        "cli_executed": False,
        "file_written": False,
        "scheduler_attached": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "writer_run_receipt_summary": {
            "run_package_id": run_package_id,
            "receipt_id": receipt_id,
            "target_table": TARGET_TABLE,
            "payload_row_count": payload_row_count,
            "writer_output_path": writer_output_path,
            "postwrite_smoke_result_path": postwrite_smoke_result_path,
            "backup_artifact_path": backup_artifact_path,
            "postwrite_smoke_read_only_by_operator": True,
            "postwrite_smoke_expected_rows_found": True,
            "postwrite_smoke_row_count_matches_payload": True,
        },
    }
    receipt = _receipt_review_summary(receipt_result)
    operator_closeout = {
        "closeout_id": "market-intel-candidate-writer-run-closeout-sample",
        "run_package_id": receipt["run_package_id"],
        "receipt_id": receipt["receipt_id"],
        "target_table": TARGET_TABLE,
        "payload_row_count": receipt["payload_row_count"],
        "closeout_artifact_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-run-closeout-sample.json"
        ),
        "receipt_review_artifact_path": (
            ARTIFACT_PREFIX
            + "candidate-queue-writer-run-receipt-review-sample.json"
        ),
        "post_closeout_inventory_plan_path": (
            ARTIFACT_PREFIX + "candidate-queue-post-closeout-inventory-plan.json"
        ),
        "rollback_note": "No API rollback executed; operator keeps DB backup path.",
        "closeout_notes": "Receipt accepted; next step is read-only live inventory.",
        "artifact_manifest": {
            "writer_output_path": receipt["writer_output_path"],
            "postwrite_smoke_result_path": receipt["postwrite_smoke_result_path"],
            "backup_artifact_path": receipt["backup_artifact_path"],
        },
        "operator_confirmations": {
            "receipt_reviewed": True,
            "artifacts_preserved": True,
            "rollback_note_recorded": True,
            "post_closeout_inventory_read_only": True,
            "no_approval_token_payload": True,
            "no_api_cli_execution": True,
            "no_api_database_write": True,
            "no_api_file_write": True,
            "no_post_closeout_query_by_api": True,
            "no_scheduler_attach": True,
        },
        "api_execution_allowed": False,
        "real_write_allowed_by_api": False,
    }
    _SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE = {
        "writer_run_receipt_review_package": receipt_package,
        "writer_run_receipt_review_result": receipt_result,
        "operator_closeout": operator_closeout,
    }
    return deepcopy(_SAMPLE_RUN_CLOSEOUT_REVIEW_PACKAGE)


def _receipt_review_summary(receipt_result):
    receipt_result = _as_dict(receipt_result)
    receipt = _as_dict(receipt_result.get("writer_run_receipt_summary"))
    side_effects_clear = bool(
        not receipt_result.get("payload_persisted")
        and not receipt_result.get("run_receipt_review_persisted")
        and not receipt_result.get("run_receipt_persisted")
        and not receipt_result.get("run_receipt_file_written")
        and not receipt_result.get("receipt_file_written")
        and not receipt_result.get("package_artifact_created")
        and not receipt_result.get("network_request_allowed")
        and not receipt_result.get("api_executes_cli")
        and not receipt_result.get("api_reads_approval_token")
        and not receipt_result.get("api_opens_database_connection")
        and not receipt_result.get("api_writes_database")
        and not receipt_result.get("api_writes_file")
        and not receipt_result.get("api_uses_external_network")
        and not receipt_result.get("postwrite_query_executed_by_api")
        and not receipt_result.get("database_write_executed")
        and not receipt_result.get("cli_executed")
        and not receipt_result.get("file_written")
        and not receipt_result.get("scheduler_attached")
        and not receipt_result.get("candidate_queue_created")
        and not receipt_result.get("candidate_queue_persisted")
    )
    return {
        "mode": receipt_result.get("mode"),
        "accepted": bool(
            receipt_result.get(
                "mcp_fetch_candidate_queue_writer_run_receipt_review_accepted"
            )
        ),
        "ready_for_closeout_review": bool(
            receipt_result.get("ready_for_candidate_queue_writer_run_closeout_review")
        ),
        "run_package_id": _safe_text(receipt.get("run_package_id"), 160),
        "receipt_id": _safe_text(receipt.get("receipt_id"), 160),
        "target_table": _safe_text(receipt.get("target_table"), 160),
        "payload_row_count": _safe_int(receipt.get("payload_row_count")),
        "writer_output_path": _safe_text(receipt.get("writer_output_path")),
        "postwrite_smoke_result_path": _safe_text(
            receipt.get("postwrite_smoke_result_path")
        ),
        "backup_artifact_path": _safe_text(receipt.get("backup_artifact_path")),
        "postwrite_smoke_read_only_by_operator": bool(
            receipt.get("postwrite_smoke_read_only_by_operator")
        ),
        "postwrite_smoke_expected_rows_found": bool(
            receipt.get("postwrite_smoke_expected_rows_found")
        ),
        "postwrite_smoke_row_count_matches_payload": bool(
            receipt.get("postwrite_smoke_row_count_matches_payload")
        ),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": receipt_result.get("blocked_reasons", []),
    }


def _operator_closeout_summary(operator_closeout):
    operator_closeout = _as_dict(operator_closeout)
    manifest = _as_dict(operator_closeout.get("artifact_manifest"))
    confirmations = _as_dict(operator_closeout.get("operator_confirmations"))
    return {
        "provided_keys": sorted(operator_closeout.keys()),
        "closeout_id": _safe_text(operator_closeout.get("closeout_id"), 160),
        "run_package_id": _safe_text(operator_closeout.get("run_package_id"), 160),
        "receipt_id": _safe_text(operator_closeout.get("receipt_id"), 160),
        "target_table": _safe_text(operator_closeout.get("target_table"), 160),
        "payload_row_count": _safe_int(operator_closeout.get("payload_row_count")),
        "closeout_artifact_path": _safe_text(
            operator_closeout.get("closeout_artifact_path")
        ),
        "receipt_review_artifact_path": _safe_text(
            operator_closeout.get("receipt_review_artifact_path")
        ),
        "post_closeout_inventory_plan_path": _safe_text(
            operator_closeout.get("post_closeout_inventory_plan_path")
        ),
        "closeout_artifact_path_safe": _safe_path(
            operator_closeout.get("closeout_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "receipt_review_artifact_path_safe": _safe_path(
            operator_closeout.get("receipt_review_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "post_closeout_inventory_plan_path_safe": _safe_path(
            operator_closeout.get("post_closeout_inventory_plan_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "manifest_writer_output_path": _safe_text(manifest.get("writer_output_path")),
        "manifest_postwrite_smoke_result_path": _safe_text(
            manifest.get("postwrite_smoke_result_path")
        ),
        "manifest_backup_artifact_path": _safe_text(
            manifest.get("backup_artifact_path")
        ),
        "manifest_writer_output_path_safe": _safe_path(
            manifest.get("writer_output_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "manifest_postwrite_smoke_result_path_safe": _safe_path(
            manifest.get("postwrite_smoke_result_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "manifest_backup_artifact_path_safe": _safe_path(
            manifest.get("backup_artifact_path"),
            prefixes=(BACKUP_PREFIX,),
            suffixes=(".zip", ".tar.gz"),
        ),
        "rollback_note_recorded": bool(_safe_text(operator_closeout.get("rollback_note"))),
        "closeout_notes_recorded": bool(_safe_text(operator_closeout.get("closeout_notes"))),
        "receipt_reviewed": bool(confirmations.get("receipt_reviewed")),
        "artifacts_preserved": bool(confirmations.get("artifacts_preserved")),
        "operator_rollback_note_recorded": bool(
            confirmations.get("rollback_note_recorded")
        ),
        "post_closeout_inventory_read_only": bool(
            confirmations.get("post_closeout_inventory_read_only")
        ),
        "no_approval_token_payload": bool(
            confirmations.get("no_approval_token_payload")
        ),
        "no_api_cli_execution": bool(confirmations.get("no_api_cli_execution")),
        "no_api_database_write": bool(confirmations.get("no_api_database_write")),
        "no_api_file_write": bool(confirmations.get("no_api_file_write")),
        "no_post_closeout_query_by_api": bool(
            confirmations.get("no_post_closeout_query_by_api")
        ),
        "no_scheduler_attach": bool(confirmations.get("no_scheduler_attach")),
        "api_execution_allowed": bool(operator_closeout.get("api_execution_allowed")),
        "real_write_allowed_by_api": bool(
            operator_closeout.get("real_write_allowed_by_api")
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            operator_closeout,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_side_effects(operator_closeout),
    }


def _closeout_gates(*, receipt_received, closeout_received, receipt, closeout):
    artifact_manifest_matches = bool(
        closeout["manifest_writer_output_path"]
        and closeout["manifest_writer_output_path"] == receipt["writer_output_path"]
        and closeout["manifest_postwrite_smoke_result_path"]
        == receipt["postwrite_smoke_result_path"]
        and closeout["manifest_backup_artifact_path"] == receipt["backup_artifact_path"]
    )
    artifact_manifest_paths_safe = bool(
        closeout["manifest_writer_output_path_safe"]
        and closeout["manifest_postwrite_smoke_result_path_safe"]
        and closeout["manifest_backup_artifact_path_safe"]
    )
    operator_confirmed_boundaries = bool(
        closeout["receipt_reviewed"]
        and closeout["artifacts_preserved"]
        and closeout["operator_rollback_note_recorded"]
        and closeout["post_closeout_inventory_read_only"]
        and closeout["no_approval_token_payload"]
        and closeout["no_api_cli_execution"]
        and closeout["no_api_database_write"]
        and closeout["no_api_file_write"]
        and closeout["no_post_closeout_query_by_api"]
        and closeout["no_scheduler_attach"]
    )
    return [
        {
            "key": "writer_run_receipt_review_payload_or_result_received",
            "label": "已提供 writer run receipt review package 或已審核結果",
            "passed": receipt_received,
        },
        {
            "key": "writer_run_receipt_review_accepted",
            "label": "writer run receipt review gate 必須已通過",
            "passed": receipt["accepted"],
        },
        {
            "key": "writer_run_receipt_review_ready_for_closeout",
            "label": "receipt review 必須只放行到 closeout review",
            "passed": receipt["ready_for_closeout_review"],
        },
        {
            "key": "writer_run_receipt_review_side_effect_free",
            "label": "receipt review 未顯示 API 執行、寫 DB、寫檔或掛 scheduler",
            "passed": receipt["side_effects_clear"],
        },
        {
            "key": "writer_run_receipt_review_identity_recorded",
            "label": "receipt review 必須保留 run_package_id 與 receipt_id",
            "passed": bool(receipt["run_package_id"] and receipt["receipt_id"]),
        },
        {
            "key": "writer_run_receipt_review_postwrite_smoke_passed",
            "label": "receipt review 的 post-write smoke 必須是操作員只讀且 row count 對齊",
            "passed": bool(
                receipt["postwrite_smoke_read_only_by_operator"]
                and receipt["postwrite_smoke_expected_rows_found"]
                and receipt["postwrite_smoke_row_count_matches_payload"]
            ),
        },
        {
            "key": "writer_run_closeout_payload_received",
            "label": "已提供 operator closeout 摘要",
            "passed": closeout_received,
        },
        {
            "key": "writer_run_closeout_identity_recorded",
            "label": "closeout 必須記錄 closeout_id、run_package_id 與 receipt_id",
            "passed": bool(
                closeout["closeout_id"]
                and closeout["run_package_id"]
                and closeout["receipt_id"]
            ),
        },
        {
            "key": "writer_run_closeout_identity_matches_receipt",
            "label": "closeout run_package_id / receipt_id 必須對齊 receipt review",
            "passed": bool(
                closeout["run_package_id"] == receipt["run_package_id"]
                and closeout["receipt_id"] == receipt["receipt_id"]
            ),
        },
        {
            "key": "writer_run_closeout_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": closeout["target_table"] == TARGET_TABLE,
        },
        {
            "key": "writer_run_closeout_payload_count_matches_receipt",
            "label": "closeout row count 必須對齊 receipt review",
            "passed": bool(
                closeout["payload_row_count"]
                and closeout["payload_row_count"] == receipt["payload_row_count"]
            ),
        },
        {
            "key": "writer_run_closeout_artifact_paths_safe",
            "label": "closeout、receipt review 與 post-closeout inventory plan paths 必須安全",
            "passed": bool(
                closeout["closeout_artifact_path_safe"]
                and closeout["receipt_review_artifact_path_safe"]
                and closeout["post_closeout_inventory_plan_path_safe"]
            ),
        },
        {
            "key": "writer_run_closeout_artifact_manifest_preserved",
            "label": "closeout artifact manifest 必須保留 writer output、post-write smoke 與 backup path",
            "passed": bool(artifact_manifest_matches and artifact_manifest_paths_safe),
        },
        {
            "key": "writer_run_closeout_notes_recorded",
            "label": "closeout 必須記錄 closeout notes 與 rollback note",
            "passed": bool(
                closeout["closeout_notes_recorded"]
                and closeout["rollback_note_recorded"]
            ),
        },
        {
            "key": "writer_run_closeout_operator_boundaries_confirmed",
            "label": "操作員確認 artifact 保存、只讀 inventory、無 API DB/CLI/file/scheduler",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "writer_run_closeout_no_api_execution_or_real_write",
            "label": "closeout payload 不得允許 API execution 或 real write",
            "passed": bool(
                not closeout["api_execution_allowed"]
                and not closeout["real_write_allowed_by_api"]
            ),
        },
        {
            "key": "writer_run_closeout_no_secret_or_token_key",
            "label": "closeout payload 不得包含 secret、cookie、password 或 token key",
            "passed": not closeout["secret_or_token_submitted_to_api"],
        },
        {
            "key": "writer_run_closeout_side_effect_free",
            "label": "closeout payload 不得要求 API 寫檔、執行、寫 DB 或掛 scheduler",
            "passed": not closeout["blocked_side_effects"],
        },
    ]


def build_mcp_fetch_candidate_queue_writer_run_closeout_review_preview(
    *,
    writer_run_receipt_review_package=None,
    writer_run_receipt_review_result=None,
    operator_closeout=None,
    phase=None,
):
    """建立 fetch candidate queue writer run closeout review；不執行查詢或寫入。"""
    writer_run_receipt_review_package = _as_dict(writer_run_receipt_review_package)
    receipt_result_received = bool(
        isinstance(writer_run_receipt_review_result, dict)
        and writer_run_receipt_review_result
    )
    closeout_valid_object = (
        isinstance(operator_closeout, dict) if operator_closeout is not None else True
    )
    closeout_payload = _as_dict(operator_closeout)
    receipt_received = bool(
        writer_run_receipt_review_package or receipt_result_received
    )
    receipt_result = (
        _receipt_review_from_inputs(
            writer_run_receipt_review_package,
            writer_run_receipt_review_result,
            phase,
        )
        if receipt_received
        else {}
    )
    payload_received = bool(
        receipt_received or closeout_payload or operator_closeout is not None
    )
    closeout_received = bool(closeout_payload)
    receipt = _receipt_review_summary(receipt_result)
    closeout = _operator_closeout_summary(closeout_payload)
    gates = _closeout_gates(
        receipt_received=receipt_received,
        closeout_received=closeout_received and closeout_valid_object,
        receipt=receipt,
        closeout=closeout,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    if not closeout_valid_object:
        blocked_reasons.append("operator_closeout_payload_valid_object")
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_run_closeout_review"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_run_closeout_review_preview"
        ),
        "phase": phase,
        "writer_run_closeout_review_payload_received": payload_received,
        "writer_run_receipt_review_received": receipt_received,
        "operator_closeout_received": closeout_received,
        "operator_closeout_valid_object": closeout_valid_object,
        "writer_run_receipt_review_accepted": receipt["accepted"],
        "mcp_fetch_candidate_queue_writer_run_closeout_review_accepted": accepted,
        "candidate_queue_writer_run_closeout_review_ready": accepted,
        "ready_for_candidate_queue_post_closeout_inventory_review": accepted,
        "ready_for_api_database_write": False,
        "ready_for_real_write": False,
        "ready_for_scheduler_attach": False,
        "network_request_allowed": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_uses_external_network": False,
        "post_closeout_query_executed_by_api": False,
        "payload_row_count": closeout["payload_row_count"],
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "writer_run_receipt_review_summary": receipt,
        "operator_closeout_summary": closeout,
        "sample_writer_run_closeout_review_package": (
            _sample_run_closeout_review_package()
        ),
        "next_operator_steps": [
            "Closeout review 通過後，只代表可進入 post-closeout live inventory read-only review",
            "API/UI 仍不得回放 receipt 原文、執行 CLI、讀 token、開 DB 或寫 queue",
            "後續 live inventory 必須只讀確認 queue row，不得在 UI/API 補寫資料或掛 scheduler",
        ],
        "payload_persisted": False,
        "run_closeout_review_persisted": False,
        "run_closeout_persisted": False,
        "run_closeout_file_written": False,
        "closeout_file_written": False,
        "package_artifact_created": False,
        "database_session_created": False,
        "database_commit_executed": False,
        "database_write_executed": False,
        "external_network_executed": False,
        "cli_executed": False,
        "file_written": False,
        "writes_executed": False,
        "would_write_database": False,
        "scheduler_attached": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "candidate_review_state_updated": False,
    }
