"""Gate checks for market intel review decision approval."""

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_gates import (
    ALLOWED_REVIEW_DECISIONS,
)

ALLOWED_APPROVAL_RESULTS = ("approved_for_writer_preflight",)


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


def _approval_rows_match_decision(decision, approval):
    decision_rows = {
        row["dedupe_key"]: row for row in decision["decision_rows"]
    }
    if not decision_rows or not approval["approval_rows"]:
        return False
    for row in approval["approval_rows"]:
        source = decision_rows.get(row["dedupe_key"])
        if not source:
            return False
        if row["current_review_state"] != source["current_review_state"]:
            return False
        if row["proposed_review_decision"] != source["proposed_review_decision"]:
            return False
        if row["approved_review_decision"] != source["proposed_review_decision"]:
            return False
        if row["decision_evidence_ref"] != source["evidence_ref"]:
            return False
    return True


def _all_rows_have_allowed_decisions(approval):
    return bool(
        approval["approval_rows"]
        and all(
            row["proposed_review_decision"] in ALLOWED_REVIEW_DECISIONS
            and row["approved_review_decision"] in ALLOWED_REVIEW_DECISIONS
            and row["approval_result"] in ALLOWED_APPROVAL_RESULTS
            for row in approval["approval_rows"]
        )
    )


def _all_rows_have_approval_evidence(approval):
    return bool(
        approval["approval_rows"]
        and all(
            row["approval_notes_present"]
            and row["decision_evidence_ref_safe"]
            and row["approval_evidence_ref_safe"]
            for row in approval["approval_rows"]
        )
    )


def _matched_rows_keep_identity_guards(approval):
    matched_rows = [
        row
        for row in approval["approval_rows"]
        if row["approved_review_decision"] == "matched"
        or row.get("proposed_review_decision") == "matched"
        or row.get("original_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_approval_gates(
    *, decision_received, approval_received, decision, approval
):
    operator_confirmed_boundaries = bool(
        approval["review_decision_checked"]
        and approval["approval_is_human_only"]
        and approval["manual_record_required"]
        and approval["no_approval_token_payload"]
        and approval["no_api_cli_execution"]
        and approval["no_api_database_write"]
        and approval["no_api_review_state_update"]
        and approval["no_api_decision_record_write"]
        and approval["no_api_match_write"]
        and approval["no_api_queue_insert"]
        and approval["no_api_file_write"]
        and approval["no_scheduler_attach"]
        and approval["stronger_existing_match_guard_preserved"]
        and approval["false_positive_guard_completed"]
        and approval["variant_sensitive_review_completed"]
        and approval["hard_veto_respected"]
        and approval["decision_rows_match_review_decision"]
    )
    return [
        {
            "key": "candidate_queue_review_decision_payload_or_result_received",
            "label": "已提供 review decision package 或已審核結果",
            "passed": decision_received,
        },
        {
            "key": "candidate_queue_review_decision_accepted",
            "label": "review decision gate 必須已通過",
            "passed": decision["accepted"],
        },
        {
            "key": "candidate_queue_review_decision_ready_for_approval",
            "label": "decision 必須只放行到 approval gate",
            "passed": decision["ready_for_candidate_queue_review_decision_approval"],
        },
        {
            "key": "candidate_queue_review_decision_side_effect_free",
            "label": "decision 未顯示 API 執行、寫 DB、寫 decision、更新 review_state 或掛 scheduler",
            "passed": decision["side_effects_clear"],
        },
        {
            "key": "candidate_queue_review_decision_approval_payload_received",
            "label": "已提供 operator approval 摘要",
            "passed": approval_received,
        },
        {
            "key": "candidate_queue_review_decision_approval_identity_recorded",
            "label": "approval 必須記錄 approval_id 與上游 identity",
            "passed": bool(
                approval["approval_id"]
                and approval["review_decision_id"]
                and approval["review_inventory_id"]
                and approval["handoff_id"]
                and approval["inventory_review_id"]
                and approval["closeout_id"]
                and approval["run_package_id"]
                and approval["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_identity_matches_decision",
            "label": "approval identity 必須對齊 review decision",
            "passed": bool(
                approval["review_decision_id"] == decision["review_decision_id"]
                and approval["review_inventory_id"] == decision["review_inventory_id"]
                and approval["handoff_id"] == decision["handoff_id"]
                and approval["inventory_review_id"] == decision["inventory_review_id"]
                and approval["closeout_id"] == decision["closeout_id"]
                and approval["run_package_id"] == decision["run_package_id"]
                and approval["receipt_id"] == decision["receipt_id"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": approval["target_table"] == TARGET_TABLE,
        },
        {
            "key": "candidate_queue_review_decision_approval_scope_safe",
            "label": "approval 僅能是 human approval only",
            "passed": bool(
                approval["approval_scope"] == "candidate_queue_review_decision_approval"
                and approval["approval_mode"] == "human_approval_only"
                and approval["expected_decision_scope"]
                == "candidate_queue_review_decision"
                and approval["expected_current_review_state"] == "needs_review"
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_row_count_matches_decision",
            "label": "approval row count 必須對齊 decision row count",
            "passed": bool(
                approval["expected_approved_row_count"]
                and approval["approval_row_count"]
                == approval["expected_approved_row_count"]
                == decision["decision_row_count"]
                and len(approval["approval_rows"]) == decision["decision_row_count"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_rows_match_decision",
            "label": "approval rows 必須逐列對齊 decision rows",
            "passed": bool(
                _row_keys_match_expected(approval)
                and _approval_rows_match_decision(decision, approval)
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_values_allowed",
            "label": "approval 只能批准允許的決策集合",
            "passed": _all_rows_have_allowed_decisions(approval),
        },
        {
            "key": "candidate_queue_review_decision_approval_row_evidence_complete",
            "label": "每列 approval 必須保留 evidence ref 與 notes",
            "passed": _all_rows_have_approval_evidence(approval),
        },
        {
            "key": "candidate_queue_review_decision_approval_matched_rows_keep_identity_guards",
            "label": "matched approvals 必須保留 exact identity、variant 與 overwrite guard",
            "passed": _matched_rows_keep_identity_guards(approval),
        },
        {
            "key": "candidate_queue_review_decision_approval_artifact_paths_safe",
            "label": "review queue、inventory、decision 與 approval artifact paths 必須安全並對齊",
            "passed": bool(
                approval["review_queue_artifact_path_safe"]
                and approval["review_inventory_artifact_path_safe"]
                and approval["review_decision_artifact_path_safe"]
                and approval["approval_artifact_path_safe"]
                and approval["review_queue_artifact_path"]
                == decision["review_queue_artifact_path"]
                and approval["review_inventory_artifact_path"]
                == decision["review_inventory_artifact_path"]
                and approval["review_decision_artifact_path"]
                == decision["review_decision_artifact_path"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_operator_boundaries_confirmed",
            "label": "操作員確認 API 未執行 CLI/DB/file/review_state/decision/match/scheduler",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "candidate_queue_review_decision_approval_no_api_execution_or_real_write",
            "label": "approval payload 不得允許 API execution、real write、review update、decision write 或 match write",
            "passed": bool(
                not approval["api_execution_allowed"]
                and not approval["real_write_allowed_by_api"]
                and not approval["api_candidate_review_allowed"]
                and not approval["api_updates_review_state"]
                and not approval["api_writes_approval_record"]
                and not approval["api_writes_decision_record"]
                and not approval["api_writes_match_result"]
            ),
        },
        {
            "key": "candidate_queue_review_decision_approval_no_secret_or_token_key",
            "label": "approval payload 不得包含 secret、cookie、password 或 token key",
            "passed": not approval["secret_or_token_submitted_to_api"],
        },
        {
            "key": "candidate_queue_review_decision_approval_side_effect_free",
            "label": "approval payload 不得要求 API 寫檔、執行、寫 DB、補 queue、寫 match 或掛 scheduler",
            "passed": not approval["blocked_side_effects"],
        },
    ]
