"""Gate checks for market intel candidate queue review inventory."""

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE


def _review_state_breakdown_is_safe(inventory):
    breakdown = inventory["review_state_breakdown"]
    if not breakdown:
        return False
    if any(value for key, value in breakdown.items() if key != "needs_review"):
        return False
    return breakdown.get("needs_review", 0) == inventory["found_row_count"]


def build_review_inventory_gates(*, handoff_received, inventory_received, handoff, inventory):
    operator_confirmed_boundaries = bool(
        inventory["handoff_reviewed"]
        and inventory["review_inventory_read_only"]
        and inventory["candidate_queue_review_only"]
        and inventory["manual_review_required"]
        and inventory["no_missing_rows"]
        and inventory["no_unexpected_duplicates"]
        and inventory["no_approval_token_payload"]
        and inventory["no_api_cli_execution"]
        and inventory["no_api_database_write"]
        and inventory["no_api_inventory_query"]
        and inventory["no_api_review_state_update"]
        and inventory["no_api_queue_insert"]
        and inventory["no_api_file_write"]
        and inventory["no_scheduler_attach"]
    )
    read_only_query_safe = bool(
        inventory["query_type"] == "read_only_select"
        and inventory["read_only_query_executed_by_operator"]
        and inventory["query_target_table"] == TARGET_TABLE
        and inventory["expected_rows_found"]
        and inventory["row_count_matches_handoff"]
        and inventory["review_state_only_needs_review"]
        and inventory["no_missing_dedupe_keys"]
        and inventory["query_no_unexpected_duplicates"]
    )
    return [
        {
            "key": "candidate_queue_review_handoff_payload_or_result_received",
            "label": "已提供 review handoff package 或已審核結果",
            "passed": handoff_received,
        },
        {
            "key": "candidate_queue_review_handoff_accepted",
            "label": "review handoff gate 必須已通過",
            "passed": handoff["accepted"],
        },
        {
            "key": "candidate_queue_review_handoff_ready_for_inventory",
            "label": "handoff 必須只放行到 candidate queue review inventory",
            "passed": handoff["ready_for_candidate_queue_review_inventory"],
        },
        {
            "key": "candidate_queue_review_handoff_side_effect_free",
            "label": "handoff 未顯示 API 執行、寫 DB、寫檔、查 DB、更新 review_state 或掛 scheduler",
            "passed": handoff["side_effects_clear"],
        },
        {
            "key": "candidate_queue_review_handoff_identity_recorded",
            "label": "handoff 必須保留 handoff_id、inventory_review_id、closeout_id、run_package_id 與 receipt_id",
            "passed": bool(
                handoff["handoff_id"]
                and handoff["inventory_review_id"]
                and handoff["closeout_id"]
                and handoff["run_package_id"]
                and handoff["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_inventory_payload_received",
            "label": "已提供 operator candidate queue review inventory 摘要",
            "passed": inventory_received,
        },
        {
            "key": "candidate_queue_review_inventory_identity_recorded",
            "label": "inventory 必須記錄 review_inventory_id、handoff_id 與上游 identity",
            "passed": bool(
                inventory["review_inventory_id"]
                and inventory["handoff_id"]
                and inventory["inventory_review_id"]
                and inventory["closeout_id"]
                and inventory["run_package_id"]
                and inventory["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_inventory_identity_matches_handoff",
            "label": "inventory identity 必須對齊 handoff",
            "passed": bool(
                inventory["handoff_id"] == handoff["handoff_id"]
                and inventory["inventory_review_id"] == handoff["inventory_review_id"]
                and inventory["closeout_id"] == handoff["closeout_id"]
                and inventory["run_package_id"] == handoff["run_package_id"]
                and inventory["receipt_id"] == handoff["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_inventory_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": inventory["target_table"] == TARGET_TABLE,
        },
        {
            "key": "candidate_queue_review_inventory_row_count_matches_handoff",
            "label": "inventory row count 必須對齊 handoff，且無缺漏或重複",
            "passed": bool(
                inventory["expected_payload_row_count"]
                and inventory["expected_payload_row_count"]
                == handoff["expected_payload_row_count"]
                and inventory["payload_row_count"] == handoff["payload_row_count"]
                and inventory["found_row_count"] == handoff["expected_payload_row_count"]
                and inventory["dedupe_key_count"] == handoff["expected_payload_row_count"]
                and inventory["missing_row_count"] == 0
                and inventory["unexpected_duplicate_count"] == 0
            ),
        },
        {
            "key": "candidate_queue_review_inventory_review_state_safe",
            "label": "盤點結果必須仍全部停在 needs_review，不得提前更新狀態",
            "passed": bool(
                inventory["review_state"] == "needs_review"
                and _review_state_breakdown_is_safe(inventory)
            ),
        },
        {
            "key": "candidate_queue_review_inventory_artifact_paths_safe",
            "label": "review queue、handoff、inventory 與 read-only query artifacts 必須安全並對齊 handoff",
            "passed": bool(
                inventory["review_queue_artifact_path_safe"]
                and inventory["handoff_artifact_path_safe"]
                and inventory["inventory_artifact_path_safe"]
                and inventory["review_inventory_artifact_path_safe"]
                and inventory["read_only_query_result_path_safe"]
                and inventory["review_queue_artifact_path"]
                == handoff["review_queue_artifact_path"]
                and inventory["handoff_artifact_path"] == handoff["handoff_artifact_path"]
                and inventory["inventory_artifact_path"]
                == handoff["inventory_artifact_path"]
            ),
        },
        {
            "key": "candidate_queue_review_inventory_scope_safe",
            "label": "inventory 僅能交接到 manual candidate queue review",
            "passed": bool(
                inventory["review_scope"] == "candidate_queue_review"
                and inventory["next_queue"] == "manual_candidate_queue_review"
            ),
        },
        {
            "key": "candidate_queue_review_inventory_read_only_query_by_operator",
            "label": "只讀查詢只能由 operator 執行，API 僅接收摘要",
            "passed": read_only_query_safe,
        },
        {
            "key": "candidate_queue_review_inventory_operator_boundaries_confirmed",
            "label": "操作員確認 API 未執行 CLI/DB/query/file/review_state/scheduler",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "candidate_queue_review_inventory_no_api_execution_or_real_write",
            "label": "inventory payload 不得允許 API execution、real write 或 API review update",
            "passed": bool(
                not inventory["api_execution_allowed"]
                and not inventory["real_write_allowed_by_api"]
                and not inventory["api_candidate_review_allowed"]
                and not inventory["api_updates_review_state"]
            ),
        },
        {
            "key": "candidate_queue_review_inventory_no_secret_or_token_key",
            "label": "inventory payload 不得包含 secret、cookie、password 或 token key",
            "passed": not inventory["secret_or_token_submitted_to_api"],
        },
        {
            "key": "candidate_queue_review_inventory_side_effect_free",
            "label": "inventory payload 不得要求 API 寫檔、執行、查 DB、寫 DB、補 queue 或掛 scheduler",
            "passed": not inventory["blocked_side_effects"],
        },
    ]
