"""市場情報 MCP fetch candidate queue writer review decision approval。

本模組只審核 review decision 後的人工 approval 摘要；
API/UI 不讀 approval token、不執行 CLI、不開 DB、不寫 decision record、
不更新 review_state、不寫 match result、不補 queue、不掛 scheduler。
"""

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,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_post_closeout_inventory_review import (
    FORBIDDEN_SECRET_KEYS,
    SAFE_SECRET_METADATA_KEYS,
    _as_dict,
    _as_list,
    _blocked_side_effects,
    _contains_forbidden_key,
    _safe_int,
    _safe_path,
    _safe_text,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision import (
    build_mcp_fetch_candidate_queue_writer_review_decision_preview,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_gates import (
    ALLOWED_REVIEW_DECISIONS,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_approval_gates import (
    ALLOWED_APPROVAL_RESULTS,
    build_review_decision_approval_gates,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_approval_sample import (
    build_sample_writer_review_decision_approval_package,
)


_APPROVAL_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_candidate_review_update",
    "allow_api_decision_record_write",
    "allow_api_execution",
    "allow_api_file_write",
    "allow_api_match_write",
    "allow_api_queue_insert",
    "allow_api_queue_write",
    "allow_cli_execution",
    "allow_database_write",
    "api_candidate_review_update_executed",
    "api_created_review_decision_file",
    "api_review_decision_persisted",
    "api_review_state_update_executed",
    "api_write_allowed",
    "api_updates_review_state",
    "api_writes_approval_record",
    "api_writes_decision_record",
    "api_writes_match_result",
    "candidate_queue_review_decision_approval_file_written",
    "candidate_queue_review_decision_approval_persisted",
    "decision_approval_file_written",
    "decision_approval_persisted",
    "decision_record_written",
    "market_product_match_written",
    "match_result_written",
    "review_state_update_executed",
)


def _blocked_approval_side_effects(payload):
    found = list(_blocked_side_effects(payload))

    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 _APPROVAL_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 sorted(set(found))


def _decision_from_inputs(decision_package, decision_result, phase):
    if isinstance(decision_result, dict) and decision_result:
        return decision_result

    decision_package = _as_dict(decision_package)
    return build_mcp_fetch_candidate_queue_writer_review_decision_preview(
        writer_review_inventory_package=(
            decision_package.get("writer_review_inventory_package")
            or decision_package.get("candidate_queue_writer_review_inventory")
            or decision_package.get("writer_review_inventory")
            or decision_package.get("review_inventory_package")
            or {}
        ),
        writer_review_inventory_result=(
            decision_package.get("writer_review_inventory_result")
            or decision_package.get(
                "mcp_fetch_candidate_queue_writer_review_inventory"
            )
        ),
        operator_review_decision=(
            decision_package.get("operator_review_decision")
            or decision_package.get("candidate_queue_review_decision")
            or decision_package.get("writer_review_decision")
            or decision_package.get("review_decision_payload")
            or decision_package.get("decision_payload")
            or decision_package.get("decision")
        ),
        phase=phase,
    )


def _decision_summary(decision_result):
    decision_result = _as_dict(decision_result)
    decision = _as_dict(decision_result.get("operator_review_decision_summary"))
    side_effects_clear = bool(
        not decision_result.get("payload_persisted")
        and not decision_result.get("review_decision_persisted")
        and not decision_result.get("candidate_queue_review_decision_persisted")
        and not decision_result.get("candidate_queue_review_decision_file_written")
        and not decision_result.get("decision_record_written")
        and not decision_result.get("decision_record_file_written")
        and not decision_result.get("api_executes_cli")
        and not decision_result.get("api_reads_approval_token")
        and not decision_result.get("api_opens_database_connection")
        and not decision_result.get("api_writes_database")
        and not decision_result.get("api_writes_file")
        and not decision_result.get("api_updates_review_state")
        and not decision_result.get("api_writes_decision_record")
        and not decision_result.get("api_writes_match_result")
        and not decision_result.get("database_write_executed")
        and not decision_result.get("database_commit_executed")
        and not decision_result.get("cli_executed")
        and not decision_result.get("file_written")
        and not decision_result.get("scheduler_attached")
        and not decision_result.get("candidate_queue_persisted")
        and not decision_result.get("candidate_review_state_updated")
    )
    return {
        "mode": decision_result.get("mode"),
        "accepted": bool(
            decision_result.get(
                "mcp_fetch_candidate_queue_writer_review_decision_accepted"
            )
        ),
        "ready_for_candidate_queue_review_decision_approval": bool(
            decision_result.get("ready_for_candidate_queue_review_decision_approval")
        ),
        "review_decision_id": _safe_text(
            decision.get("review_decision_id"), 160
        ),
        "review_inventory_id": _safe_text(decision.get("review_inventory_id"), 160),
        "handoff_id": _safe_text(decision.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(decision.get("inventory_review_id"), 160),
        "closeout_id": _safe_text(decision.get("closeout_id"), 160),
        "run_package_id": _safe_text(decision.get("run_package_id"), 160),
        "receipt_id": _safe_text(decision.get("receipt_id"), 160),
        "target_table": _safe_text(decision.get("target_table"), 160),
        "decision_scope": _safe_text(decision.get("decision_scope"), 120),
        "decision_mode": _safe_text(decision.get("decision_mode"), 120),
        "decision_row_count": _safe_int(decision.get("decision_row_count")),
        "expected_dedupe_keys": [
            _safe_text(item, 160)
            for item in _as_list(decision.get("expected_dedupe_keys"))
            if _safe_text(item, 160)
        ],
        "decision_rows": _as_list(decision.get("decision_rows")),
        "review_queue_artifact_path": _safe_text(
            decision.get("review_queue_artifact_path")
        ),
        "review_inventory_artifact_path": _safe_text(
            decision.get("review_inventory_artifact_path")
        ),
        "review_decision_artifact_path": _safe_text(
            decision.get("review_decision_artifact_path")
        ),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": decision_result.get("blocked_reasons", []),
    }


def _approval_row_summary(row):
    row = _as_dict(row)
    original_proposed_review_decision = _safe_text(
        row.get("proposed_review_decision"),
        80,
    )
    approved_review_decision = _safe_text(
        row.get("approved_review_decision") or original_proposed_review_decision,
        80,
    )
    proposed_review_decision = approved_review_decision
    decision_evidence_ref = _safe_text(
        row.get("decision_evidence_ref") or row.get("evidence_ref")
    )
    approval_evidence_ref = _safe_text(
        row.get("approval_evidence_ref")
        or row.get("approval_evidence_path")
        or row.get("evidence_ref")
    )
    return {
        "dedupe_key": _safe_text(row.get("dedupe_key"), 160),
        "current_review_state": _safe_text(row.get("current_review_state"), 80),
        "approval_result": _safe_text(row.get("approval_result"), 80),
        "original_proposed_review_decision": original_proposed_review_decision,
        "proposed_review_decision": proposed_review_decision,
        "approved_review_decision": approved_review_decision,
        "approval_bucket": _safe_text(row.get("approval_bucket"), 120),
        "evidence_lane": _safe_text(row.get("evidence_lane"), 120),
        "evidence_ref": decision_evidence_ref,
        "decision_evidence_ref": decision_evidence_ref,
        "approval_evidence_ref": approval_evidence_ref,
        "evidence_ref_safe": _safe_path(
            decision_evidence_ref,
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "decision_evidence_ref_safe": _safe_path(
            decision_evidence_ref,
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "approval_evidence_ref_safe": _safe_path(
            approval_evidence_ref,
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "approval_notes_present": bool(_safe_text(row.get("approval_notes"))),
        "hard_veto_present": bool(row.get("hard_veto_present")),
        "stronger_existing_match_conflict": bool(
            row.get("stronger_existing_match_conflict")
        ),
        "false_positive_guard_passed": bool(row.get("false_positive_guard_passed")),
        "variant_conflict_checked": bool(row.get("variant_conflict_checked")),
        "overwrite_protection_checked": bool(row.get("overwrite_protection_checked")),
        "exact_identity_confirmed": bool(row.get("exact_identity_confirmed")),
    }


def _operator_approval_summary(operator_approval):
    operator_approval = _as_dict(operator_approval)
    confirmations = _as_dict(operator_approval.get("operator_confirmations"))
    rows = [
        _approval_row_summary(row)
        for row in _as_list(
            operator_approval.get("approved_rows")
            or operator_approval.get("approval_rows")
        )
    ]
    expected_dedupe_keys = [
        _safe_text(item, 160)
        for item in _as_list(operator_approval.get("expected_dedupe_keys"))
        if _safe_text(item, 160)
    ]
    return {
        "provided_keys": sorted(operator_approval.keys()),
        "approval_id": _safe_text(
            operator_approval.get("approval_id")
            or operator_approval.get("review_decision_approval_id"),
            160,
        ),
        "review_decision_id": _safe_text(
            operator_approval.get("review_decision_id"), 160
        ),
        "review_inventory_id": _safe_text(
            operator_approval.get("review_inventory_id"), 160
        ),
        "handoff_id": _safe_text(operator_approval.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(
            operator_approval.get("inventory_review_id"), 160
        ),
        "closeout_id": _safe_text(operator_approval.get("closeout_id"), 160),
        "run_package_id": _safe_text(operator_approval.get("run_package_id"), 160),
        "receipt_id": _safe_text(operator_approval.get("receipt_id"), 160),
        "target_table": _safe_text(operator_approval.get("target_table"), 160),
        "approval_scope": _safe_text(operator_approval.get("approval_scope"), 120),
        "approval_mode": _safe_text(operator_approval.get("approval_mode"), 120),
        "expected_decision_scope": _safe_text(
            operator_approval.get("expected_decision_scope"), 120
        ),
        "expected_current_review_state": _safe_text(
            operator_approval.get("expected_current_review_state"), 80
        ),
        "approval_row_count": _safe_int(
            operator_approval.get("approval_row_count")
            or operator_approval.get("approved_row_count")
        ),
        "approved_row_count": _safe_int(
            operator_approval.get("approved_row_count")
            or operator_approval.get("approval_row_count")
        ),
        "expected_approved_row_count": _safe_int(
            operator_approval.get("expected_approved_row_count")
            or operator_approval.get("expected_approval_row_count")
            or operator_approval.get("approved_row_count")
            or operator_approval.get("approval_row_count")
        ),
        "expected_dedupe_keys": expected_dedupe_keys,
        "approval_rows": rows,
        "approved_rows": rows,
        "review_queue_artifact_path": _safe_text(
            operator_approval.get("review_queue_artifact_path")
        ),
        "review_inventory_artifact_path": _safe_text(
            operator_approval.get("review_inventory_artifact_path")
        ),
        "review_decision_artifact_path": _safe_text(
            operator_approval.get("review_decision_artifact_path")
        ),
        "approval_artifact_path": _safe_text(
            operator_approval.get("approval_artifact_path")
            or operator_approval.get("review_decision_approval_artifact_path")
        ),
        "review_decision_approval_artifact_path": _safe_text(
            operator_approval.get("review_decision_approval_artifact_path")
            or operator_approval.get("approval_artifact_path")
        ),
        "review_queue_artifact_path_safe": _safe_path(
            operator_approval.get("review_queue_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_inventory_artifact_path_safe": _safe_path(
            operator_approval.get("review_inventory_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_decision_artifact_path_safe": _safe_path(
            operator_approval.get("review_decision_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "approval_artifact_path_safe": _safe_path(
            operator_approval.get("approval_artifact_path")
            or operator_approval.get("review_decision_approval_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_decision_checked": bool(confirmations.get("review_decision_checked")),
        "approval_is_human_only": bool(
            confirmations.get("approval_is_human_only")
            or confirmations.get("human_approval_only")
        ),
        "manual_record_required": bool(
            confirmations.get("manual_record_required")
            or confirmations.get("approval_record_manual_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_review_state_update": bool(
            confirmations.get("no_api_review_state_update")
        ),
        "no_api_decision_record_write": bool(
            confirmations.get("no_api_decision_record_write")
        ),
        "no_api_match_write": bool(confirmations.get("no_api_match_write")),
        "no_api_queue_insert": bool(confirmations.get("no_api_queue_insert")),
        "no_api_file_write": bool(confirmations.get("no_api_file_write")),
        "no_scheduler_attach": bool(confirmations.get("no_scheduler_attach")),
        "stronger_existing_match_guard_preserved": bool(
            confirmations.get("stronger_existing_match_guard_preserved")
        ),
        "false_positive_guard_completed": bool(
            confirmations.get("false_positive_guard_completed")
        ),
        "variant_sensitive_review_completed": bool(
            confirmations.get("variant_sensitive_review_completed")
        ),
        "hard_veto_respected": bool(confirmations.get("hard_veto_respected")),
        "decision_rows_match_review_decision": bool(
            confirmations.get("decision_rows_match_review_decision")
        ),
        "api_execution_allowed": bool(operator_approval.get("api_execution_allowed")),
        "real_write_allowed_by_api": bool(
            operator_approval.get("real_write_allowed_by_api")
        ),
        "api_candidate_review_allowed": bool(
            operator_approval.get("api_candidate_review_allowed")
        ),
        "api_updates_review_state": bool(
            operator_approval.get("api_updates_review_state")
        ),
        "api_writes_approval_record": bool(
            operator_approval.get("api_writes_approval_record")
        ),
        "api_writes_decision_record": bool(
            operator_approval.get("api_writes_decision_record")
        ),
        "api_writes_match_result": bool(
            operator_approval.get("api_writes_match_result")
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            operator_approval,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_approval_side_effects(operator_approval),
    }


def build_mcp_fetch_candidate_queue_writer_review_decision_approval_preview(
    *,
    writer_review_decision_package=None,
    writer_review_decision_result=None,
    operator_review_decision_approval=None,
    operator_review_approval=None,
    phase=None,
):
    """建立 writer review decision approval；不執行查詢、寫檔或寫入。"""
    if operator_review_decision_approval is None:
        operator_review_decision_approval = operator_review_approval
    writer_review_decision_package = _as_dict(writer_review_decision_package)
    decision_result_received = bool(
        isinstance(writer_review_decision_result, dict)
        and writer_review_decision_result
    )
    approval_valid_object = (
        isinstance(operator_review_decision_approval, dict)
        if operator_review_decision_approval is not None
        else True
    )
    approval_payload = _as_dict(operator_review_decision_approval)
    decision_received = bool(
        writer_review_decision_package or decision_result_received
    )
    decision_result = (
        _decision_from_inputs(
            writer_review_decision_package,
            writer_review_decision_result,
            phase,
        )
        if decision_received
        else {}
    )
    payload_received = bool(
        decision_received
        or approval_payload
        or operator_review_decision_approval is not None
    )
    approval_received = bool(approval_payload)
    decision = _decision_summary(decision_result)
    approval = _operator_approval_summary(approval_payload)
    gates = build_review_decision_approval_gates(
        decision_received=decision_received,
        approval_received=approval_received and approval_valid_object,
        decision=decision,
        approval=approval,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    if not approval_valid_object:
        blocked_reasons.append("operator_review_decision_approval_payload_valid_object")
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_review_decision_approval"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_review_decision_approval_preview"
        ),
        "phase": phase,
        "writer_review_decision_approval_payload_received": payload_received,
        "approval_payload_received": payload_received,
        "writer_review_decision_received": decision_received,
        "operator_review_decision_approval_received": approval_received,
        "operator_review_decision_approval_valid_object": approval_valid_object,
        "operator_review_approval_received": approval_received,
        "operator_review_approval_valid_object": approval_valid_object,
        "writer_review_decision_accepted": decision["accepted"],
        "mcp_fetch_candidate_queue_writer_review_decision_approval_accepted": accepted,
        "candidate_queue_writer_review_decision_approval_ready": accepted,
        "ready_for_candidate_queue_review_decision_writer_preflight": accepted,
        "ready_for_candidate_queue_review_decision_approval": False,
        "ready_for_candidate_queue_review_state_writer": False,
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_api_decision_record_write": False,
        "ready_for_api_match_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,
        "api_updates_review_state": False,
        "api_writes_approval_record": False,
        "api_writes_decision_record": False,
        "api_writes_match_result": False,
        "payload_row_count": approval["approval_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_review_decision_summary": decision,
        "operator_review_decision_approval_summary": approval,
        "operator_review_approval_summary": approval,
        "approval_rows": approval["approval_rows"],
        "approved_rows": approval["approved_rows"],
        "approval_contract": {
            "expected_current_state": "needs_review",
            "allowed_next_states": list(ALLOWED_REVIEW_DECISIONS),
            "allowed_approval_results": list(ALLOWED_APPROVAL_RESULTS),
            "manual_approval_required": True,
            "next_gate": "candidate_queue_review_decision_writer_preflight",
            "approval_scope": "candidate_queue_review_decision_approval",
            "forbidden_api_actions": [
                "update_review_state",
                "write_decision_record",
                "write_match_result",
                "insert_missing_queue_row",
                "attach_scheduler",
            ],
        },
        "sample_writer_review_decision_approval_package": (
            build_sample_writer_review_decision_approval_package()
        ),
        "next_operator_steps": [
            "Approval 通過後，只代表可進入 CLI-only writer preflight 設計",
            "API/UI 仍不得自動寫 review_state、decision record 或 match result",
            "matched approval 必須保留 exact identity、variant、false-positive 與 overwrite guard",
        ],
        "payload_persisted": False,
        "review_decision_approval_persisted": False,
        "candidate_queue_review_decision_approval_persisted": False,
        "candidate_queue_review_decision_approval_file_written": False,
        "approval_record_written": False,
        "approval_record_file_written": False,
        "decision_approval_file_written": False,
        "decision_record_written": False,
        "decision_record_file_written": False,
        "match_result_written": False,
        "market_product_match_written": False,
        "package_artifact_created": False,
        "database_connection_opened": 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,
    }
