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

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE


ALLOWED_REVIEW_DECISIONS = (
    "matched",
    "low_score",
    "identity_veto",
    "unit_comparable",
    "fresh_search_required",
    "deferred",
)


def _sample_keys_covered_by_expected(inventory, decision):
    sample_keys = set(inventory["sample_dedupe_keys"])
    expected_keys = set(decision["expected_dedupe_keys"])
    return bool(sample_keys and sample_keys.issubset(expected_keys))


def _row_keys_match_expected(decision):
    row_keys = [row["dedupe_key"] for row in decision["decision_rows"]]
    expected_keys = decision["expected_dedupe_keys"]
    return bool(
        row_keys
        and len(row_keys) == len(set(row_keys))
        and set(row_keys) == set(expected_keys)
    )


def _all_rows_have_allowed_decisions(decision):
    return bool(
        decision["decision_rows"]
        and all(
            row["proposed_review_decision"] in ALLOWED_REVIEW_DECISIONS
            for row in decision["decision_rows"]
        )
    )


def _all_rows_have_manual_evidence(decision):
    return bool(
        decision["decision_rows"]
        and all(
            row["decision_notes_present"] and row["evidence_ref_safe"]
            for row in decision["decision_rows"]
        )
    )


def _matched_rows_keep_identity_guards(decision):
    matched_rows = [
        row
        for row in decision["decision_rows"]
        if row["proposed_review_decision"] == "matched"
    ]
    if not matched_rows:
        return True
    return all(
        row["evidence_lane"] == "exact_identity"
        and row["exact_identity_confirmed"]
        and not row["hard_veto_present"]
        and not row["stronger_existing_match_conflict"]
        and row["false_positive_guard_passed"]
        and row["variant_conflict_checked"]
        and row["overwrite_protection_checked"]
        for row in matched_rows
    )


def build_review_decision_gates(*, inventory_received, decision_received, inventory, decision):
    operator_confirmed_boundaries = bool(
        decision["review_inventory_checked"]
        and decision["candidate_queue_review_only"]
        and decision["human_decision_only"]
        and decision["manual_record_required"]
        and decision["no_approval_token_payload"]
        and decision["no_api_cli_execution"]
        and decision["no_api_database_write"]
        and decision["no_api_inventory_query"]
        and decision["no_api_review_state_update"]
        and decision["no_api_queue_insert"]
        and decision["no_api_file_write"]
        and decision["no_scheduler_attach"]
        and decision["stronger_existing_match_guard_preserved"]
        and decision["false_positive_guard_completed"]
        and decision["variant_sensitive_review_completed"]
        and decision["hard_veto_respected"]
    )
    return [
        {
            "key": "candidate_queue_review_inventory_payload_or_result_received",
            "label": "已提供 review inventory package 或已審核結果",
            "passed": inventory_received,
        },
        {
            "key": "candidate_queue_review_inventory_accepted",
            "label": "review inventory gate 必須已通過",
            "passed": inventory["accepted"],
        },
        {
            "key": "candidate_queue_review_inventory_ready_for_decision",
            "label": "inventory 必須只放行到 candidate queue review decision",
            "passed": inventory["ready_for_candidate_queue_review_decision"],
        },
        {
            "key": "candidate_queue_review_inventory_side_effect_free",
            "label": "inventory 未顯示 API 執行、寫 DB、查 DB、更新 review_state 或掛 scheduler",
            "passed": inventory["side_effects_clear"],
        },
        {
            "key": "candidate_queue_review_decision_payload_received",
            "label": "已提供 operator candidate queue review decision 摘要",
            "passed": decision_received,
        },
        {
            "key": "candidate_queue_review_decision_identity_recorded",
            "label": "decision 必須記錄 review_decision_id 與上游 identity",
            "passed": bool(
                decision["review_decision_id"]
                and decision["review_inventory_id"]
                and decision["handoff_id"]
                and decision["inventory_review_id"]
                and decision["closeout_id"]
                and decision["run_package_id"]
                and decision["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_identity_matches_inventory",
            "label": "decision identity 必須對齊 review inventory",
            "passed": bool(
                decision["review_inventory_id"] == inventory["review_inventory_id"]
                and decision["handoff_id"] == inventory["handoff_id"]
                and decision["inventory_review_id"] == inventory["inventory_review_id"]
                and decision["closeout_id"] == inventory["closeout_id"]
                and decision["run_package_id"] == inventory["run_package_id"]
                and decision["receipt_id"] == inventory["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": decision["target_table"] == TARGET_TABLE,
        },
        {
            "key": "candidate_queue_review_decision_scope_safe",
            "label": "decision 僅能是 human review only",
            "passed": bool(
                decision["decision_scope"] == "candidate_queue_review_decision"
                and decision["decision_mode"] == "human_review_only"
                and decision["expected_current_review_state"] == "needs_review"
            ),
        },
        {
            "key": "candidate_queue_review_decision_row_count_matches_inventory",
            "label": "decision row count 必須對齊 inventory dedupe count",
            "passed": bool(
                decision["expected_decision_row_count"]
                and decision["decision_row_count"]
                == decision["expected_decision_row_count"]
                == inventory["dedupe_key_count"]
                == inventory["found_row_count"]
                and len(decision["decision_rows"]) == inventory["dedupe_key_count"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_dedupe_keys_match_inventory",
            "label": "decision dedupe keys 必須覆蓋 inventory keys 且逐列對齊",
            "passed": bool(
                _sample_keys_covered_by_expected(inventory, decision)
                and _row_keys_match_expected(decision)
            ),
        },
        {
            "key": "candidate_queue_review_decision_rows_still_needs_review",
            "label": "所有 decision rows 的目前狀態必須仍是 needs_review",
            "passed": bool(
                decision["decision_rows"]
                and all(
                    row["current_review_state"] == "needs_review"
                    for row in decision["decision_rows"]
                )
            ),
        },
        {
            "key": "candidate_queue_review_decision_values_allowed",
            "label": "人工決策只能使用允許的狀態集合",
            "passed": _all_rows_have_allowed_decisions(decision),
        },
        {
            "key": "candidate_queue_review_decision_row_evidence_complete",
            "label": "每列決策必須保留 evidence ref 與 notes",
            "passed": _all_rows_have_manual_evidence(decision),
        },
        {
            "key": "candidate_queue_review_decision_matched_rows_keep_identity_guards",
            "label": "matched rows 必須保留 exact identity、false-positive、variant 與 overwrite guard",
            "passed": _matched_rows_keep_identity_guards(decision),
        },
        {
            "key": "candidate_queue_review_decision_artifact_paths_safe",
            "label": "review queue、inventory 與 decision artifact paths 必須安全並對齊",
            "passed": bool(
                decision["review_queue_artifact_path_safe"]
                and decision["review_inventory_artifact_path_safe"]
                and decision["review_decision_artifact_path_safe"]
                and decision["review_queue_artifact_path"]
                == inventory["review_queue_artifact_path"]
                and decision["review_inventory_artifact_path"]
                == inventory["review_inventory_artifact_path"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_operator_boundaries_confirmed",
            "label": "操作員確認 API 未執行 CLI/DB/query/file/review_state/scheduler，且 guardrail 已完成",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "candidate_queue_review_decision_no_api_execution_or_real_write",
            "label": "decision payload 不得允許 API execution、real write、review update 或 match write",
            "passed": bool(
                not decision["api_execution_allowed"]
                and not decision["real_write_allowed_by_api"]
                and not decision["api_candidate_review_allowed"]
                and not decision["api_updates_review_state"]
                and not decision["api_writes_match_result"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_no_secret_or_token_key",
            "label": "decision payload 不得包含 secret、cookie、password 或 token key",
            "passed": not decision["secret_or_token_submitted_to_api"],
        },
        {
            "key": "candidate_queue_review_decision_side_effect_free",
            "label": "decision payload 不得要求 API 寫檔、執行、查 DB、寫 DB、補 queue、寫 match 或掛 scheduler",
            "passed": not decision["blocked_side_effects"],
        },
    ]
