"""候選審核 queue 人工決策批准 gate。

本模組只檢查 decision preview 是否可進到下一個 CLI-only transaction
preview；不更新 review_state、不寫 decision record、不讀 approval token、
不掛 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"
TARGET_TABLE = "market_alert_review_queue"
ALLOWED_DECISIONS = ("confirmed", "rejected", "deferred")


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 _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 _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "decision_approval_notes_present": bool(
            str(operator_evidence.get("decision_approval_notes") or "").strip()
        ),
        "operator_confirmed_decision_payload_reviewed": bool(
            operator_evidence.get("operator_confirmed_decision_payload_reviewed")
        ),
        "operator_confirmed_decision_apply_requires_cli": bool(
            operator_evidence.get("operator_confirmed_decision_apply_requires_cli")
        ),
        "operator_confirmed_review_state_update_is_not_api": bool(
            operator_evidence.get("operator_confirmed_review_state_update_is_not_api")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _decision_update_preview(review_decision):
    rows = []
    for row in _as_list(_as_dict(review_decision).get("decision_rows")):
        row = _as_dict(row)
        rows.append(
            {
                "dedupe_key": row.get("dedupe_key"),
                "expected_current_review_state": row.get("current_review_state"),
                "approved_next_review_state": row.get("proposed_review_state"),
                "priority_lane": row.get("priority_lane"),
                "total_score": row.get("total_score"),
                "write_status": "blocked_approval_preview_only",
            }
        )
    return rows


def _approval_gates(review_decision, operator_summary, update_preview):
    return [
        {
            "key": "decision_preview_ready",
            "label": "上一階段 decision preview 必須通過",
            "passed": bool(
                review_decision.get("mode") == "candidate_queue_review_decision_preview"
                and review_decision.get("decision_ready")
            ),
        },
        {
            "key": "decision_rows_present",
            "label": "必須有人工決策 row 可轉成 update preview",
            "passed": bool(update_preview),
        },
        {
            "key": "decision_transition_allowed",
            "label": "只能從 needs_review 轉為 confirmed / rejected / deferred",
            "passed": bool(
                update_preview
                and all(
                    row.get("expected_current_review_state") == "needs_review"
                    and row.get("approved_next_review_state") in ALLOWED_DECISIONS
                    for row in update_preview
                )
            ),
        },
        {
            "key": "human_decision_record_ready",
            "label": "decision preview 必須可交給人工紀錄",
            "passed": bool(review_decision.get("ready_for_human_decision_record")),
        },
        {
            "key": "operator_reviewed_decision_payload",
            "label": "操作員確認已人工檢查 decision payload",
            "passed": bool(
                operator_summary["operator_confirmed_decision_payload_reviewed"]
            ),
        },
        {
            "key": "operator_confirmed_cli_only_apply",
            "label": "操作員確認 review_state 更新只能走 CLI-only 流程",
            "passed": bool(
                operator_summary["operator_confirmed_decision_apply_requires_cli"]
                and operator_summary[
                    "operator_confirmed_review_state_update_is_not_api"
                ]
            ),
        },
        {
            "key": "operator_confirmed_no_api_db_write_or_scheduler",
            "label": "操作員確認本 API 不寫 DB、不掛 scheduler",
            "passed": bool(
                operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "decision_approval_notes_present",
            "label": "批准 gate 需留下 notes，方便後續稽核",
            "passed": bool(operator_summary["decision_approval_notes_present"]),
        },
        {
            "key": "approval_no_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator_summary["approval_token_submitted_to_api"],
        },
    ]


def build_candidate_queue_review_decision_approval(
    *,
    review_decision,
    operator_evidence=None,
):
    """建立人工決策批准 gate；不執行 DB update。"""
    review_decision = _as_dict(review_decision)
    operator_summary = _operator_summary(operator_evidence)
    update_preview = _decision_update_preview(review_decision)
    gates = _approval_gates(review_decision, operator_summary, update_preview)
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    approval_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_decision_approval_preview",
        "target_table": TARGET_TABLE,
        "approval_ready": approval_ready,
        "ready_for_review_state_transaction_preview": approval_ready,
        "ready_for_cli_decision_writer": approval_ready,
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "review_state_update_allowed_from_api": False,
        "decision_apply_allowed_from_api": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "approval_record_written": False,
        "decision_record_written": False,
        "review_state_update_executed": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "explicit_transaction_opened": 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,
        "decision_update_preview": update_preview,
        "operator_approval_summary": operator_summary,
        "blocked_reasons": blocked_reasons,
        "approval_gates": gates,
        "approval_summary": {
            "target_table": TARGET_TABLE,
            "row_preview_count": len(update_preview),
            "allowed_next_states": list(ALLOWED_DECISIONS),
            "manual_approval_required": True,
            "api_write_allowed": False,
        },
        "approval_contract": {
            "lookup_key": "dedupe_key",
            "expected_current_state": "needs_review",
            "allowed_next_states": list(ALLOWED_DECISIONS),
            "next_stage": "candidate_queue_review_decision_transaction_preview",
            "forbidden_api_actions": [
                "update_review_state",
                "write_decision_record",
                "execute_cli",
                "attach_scheduler",
            ],
        },
        "next_operator_steps": [
            "人工確認 decision row 的 dedupe key 與 evidence_json 一致",
            "確認 next state 僅為 confirmed / rejected / deferred",
            "下一階段只產生 CLI-only transaction preview，不由 API/UI 寫入",
            "若需要真正更新 review_state，必須另開正式 shell 寫入窗口",
        ],
        "safe_boundaries": [
            "do_not_update_review_state_from_approval_api",
            "do_not_write_decision_record_from_approval_api",
            "do_not_read_approval_token_from_approval_api",
            "do_not_execute_cli_from_approval_api",
            "do_not_attach_scheduler_from_approval_api",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
