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

本模組只審核 review inventory 後的人工候選隊列決策摘要；
API/UI 不讀 approval token、不執行 CLI、不開 DB、不寫 queue、不做 inventory query、
不更新 review_state、不寫 match result、不掛 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_inventory import (
    build_mcp_fetch_candidate_queue_writer_review_inventory_preview,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_gates import (
    ALLOWED_REVIEW_DECISIONS,
    build_review_decision_gates,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_decision_sample import (
    build_sample_writer_review_decision_package,
)


_REVIEW_DECISION_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_candidate_review_update",
    "allow_api_execution",
    "allow_api_file_write",
    "allow_api_inventory_query",
    "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_created_review_queue",
    "api_executed_candidate_review",
    "api_inventory_query_executed",
    "api_review_decision_persisted",
    "api_review_state_update_executed",
    "api_updates_review_state",
    "api_writes_match_result",
    "api_writes_review_queue",
    "candidate_queue_review_decision_file_written",
    "candidate_queue_review_decision_persisted",
    "candidate_queue_review_started_by_api",
    "candidate_review_file_written",
    "candidate_review_queue_written",
    "decision_record_written",
    "identity_match_written",
    "manual_review_record_written",
    "market_product_match_written",
    "match_result_written",
    "queue_review_persisted",
    "review_decision_file_written",
    "review_decision_persisted",
    "review_queue_file_written",
    "review_queue_row_written",
    "review_state_update_executed",
)


def _blocked_review_decision_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 _REVIEW_DECISION_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 _inventory_from_inputs(inventory_package, inventory_result, phase):
    if isinstance(inventory_result, dict) and inventory_result:
        return inventory_result

    inventory_package = _as_dict(inventory_package)
    return build_mcp_fetch_candidate_queue_writer_review_inventory_preview(
        writer_review_handoff_package=(
            inventory_package.get("writer_review_handoff_package")
            or inventory_package.get("candidate_queue_writer_review_handoff")
            or inventory_package.get("writer_review_handoff")
            or inventory_package.get("review_handoff_package")
            or inventory_package.get("review_handoff")
            or {}
        ),
        writer_review_handoff_result=(
            inventory_package.get("writer_review_handoff_result")
            or inventory_package.get(
                "mcp_fetch_candidate_queue_writer_review_handoff"
            )
        ),
        operator_review_inventory=(
            inventory_package.get("operator_review_inventory")
            or inventory_package.get("candidate_queue_review_inventory")
            or inventory_package.get("writer_review_inventory")
            or inventory_package.get("review_inventory_payload")
            or inventory_package.get("inventory_payload")
            or inventory_package.get("inventory")
        ),
        phase=phase,
    )


def _inventory_summary(inventory_result):
    inventory_result = _as_dict(inventory_result)
    inventory = _as_dict(inventory_result.get("operator_review_inventory_summary"))
    side_effects_clear = bool(
        not inventory_result.get("payload_persisted")
        and not inventory_result.get("review_inventory_persisted")
        and not inventory_result.get("writer_review_inventory_persisted")
        and not inventory_result.get("candidate_queue_review_inventory_persisted")
        and not inventory_result.get("candidate_queue_review_inventory_file_written")
        and not inventory_result.get("review_inventory_file_written")
        and not inventory_result.get("inventory_file_written")
        and not inventory_result.get("review_queue_file_written")
        and not inventory_result.get("candidate_review_file_written")
        and not inventory_result.get("package_artifact_created")
        and not inventory_result.get("network_request_allowed")
        and not inventory_result.get("api_executes_cli")
        and not inventory_result.get("api_reads_approval_token")
        and not inventory_result.get("api_opens_database_connection")
        and not inventory_result.get("api_writes_database")
        and not inventory_result.get("api_writes_file")
        and not inventory_result.get("api_uses_external_network")
        and not inventory_result.get("api_inventory_query_executed")
        and not inventory_result.get("api_candidate_review_update_executed")
        and not inventory_result.get("api_updates_review_state")
        and not inventory_result.get("review_inventory_query_executed_by_api")
        and not inventory_result.get("database_write_executed")
        and not inventory_result.get("database_commit_executed")
        and not inventory_result.get("cli_executed")
        and not inventory_result.get("file_written")
        and not inventory_result.get("scheduler_attached")
        and not inventory_result.get("candidate_queue_created")
        and not inventory_result.get("candidate_queue_persisted")
        and not inventory_result.get("candidate_review_state_updated")
    )
    return {
        "mode": inventory_result.get("mode"),
        "accepted": bool(
            inventory_result.get(
                "mcp_fetch_candidate_queue_writer_review_inventory_accepted"
            )
        ),
        "ready_for_candidate_queue_review_decision": bool(
            inventory_result.get("ready_for_candidate_queue_review_decision")
        ),
        "review_inventory_id": _safe_text(
            inventory.get("review_inventory_id"), 160
        ),
        "handoff_id": _safe_text(inventory.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(inventory.get("inventory_review_id"), 160),
        "closeout_id": _safe_text(inventory.get("closeout_id"), 160),
        "run_package_id": _safe_text(inventory.get("run_package_id"), 160),
        "receipt_id": _safe_text(inventory.get("receipt_id"), 160),
        "target_table": _safe_text(inventory.get("target_table"), 160),
        "payload_row_count": _safe_int(inventory.get("payload_row_count")),
        "expected_payload_row_count": _safe_int(
            inventory.get("expected_payload_row_count")
            or inventory.get("payload_row_count")
        ),
        "found_row_count": _safe_int(inventory.get("found_row_count")),
        "dedupe_key_count": _safe_int(inventory.get("dedupe_key_count")),
        "sample_dedupe_keys": [
            _safe_text(item, 160)
            for item in _as_list(inventory.get("sample_dedupe_keys"))
            if _safe_text(item, 160)
        ],
        "review_state": _safe_text(inventory.get("review_state"), 80),
        "review_state_breakdown": _as_dict(inventory.get("review_state_breakdown")),
        "review_queue_artifact_path": _safe_text(
            inventory.get("review_queue_artifact_path")
        ),
        "review_inventory_artifact_path": _safe_text(
            inventory.get("review_inventory_artifact_path")
        ),
        "read_only_query_result_path": _safe_text(
            inventory.get("read_only_query_result_path")
        ),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": inventory_result.get("blocked_reasons", []),
    }


def _decision_row_summary(row):
    row = _as_dict(row)
    return {
        "dedupe_key": _safe_text(row.get("dedupe_key"), 160),
        "current_review_state": _safe_text(row.get("current_review_state"), 80),
        "proposed_review_decision": _safe_text(
            row.get("proposed_review_decision"), 80
        ),
        "decision_bucket": _safe_text(row.get("decision_bucket"), 120),
        "evidence_lane": _safe_text(row.get("evidence_lane"), 120),
        "evidence_ref": _safe_text(row.get("evidence_ref")),
        "evidence_ref_safe": _safe_path(
            row.get("evidence_ref"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "decision_notes_present": bool(_safe_text(row.get("decision_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_review_decision_summary(operator_decision):
    operator_decision = _as_dict(operator_decision)
    confirmations = _as_dict(operator_decision.get("operator_confirmations"))
    rows = [_decision_row_summary(row) for row in _as_list(
        operator_decision.get("decision_rows")
    )]
    expected_dedupe_keys = [
        _safe_text(item, 160)
        for item in _as_list(operator_decision.get("expected_dedupe_keys"))
        if _safe_text(item, 160)
    ]
    return {
        "provided_keys": sorted(operator_decision.keys()),
        "review_decision_id": _safe_text(
            operator_decision.get("review_decision_id"), 160
        ),
        "review_inventory_id": _safe_text(
            operator_decision.get("review_inventory_id"), 160
        ),
        "handoff_id": _safe_text(operator_decision.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(
            operator_decision.get("inventory_review_id"), 160
        ),
        "closeout_id": _safe_text(operator_decision.get("closeout_id"), 160),
        "run_package_id": _safe_text(operator_decision.get("run_package_id"), 160),
        "receipt_id": _safe_text(operator_decision.get("receipt_id"), 160),
        "target_table": _safe_text(operator_decision.get("target_table"), 160),
        "decision_scope": _safe_text(operator_decision.get("decision_scope"), 120),
        "decision_mode": _safe_text(operator_decision.get("decision_mode"), 120),
        "expected_current_review_state": _safe_text(
            operator_decision.get("expected_current_review_state"), 80
        ),
        "decision_row_count": _safe_int(operator_decision.get("decision_row_count")),
        "expected_decision_row_count": _safe_int(
            operator_decision.get("expected_decision_row_count")
            or operator_decision.get("decision_row_count")
        ),
        "expected_dedupe_keys": expected_dedupe_keys,
        "decision_rows": rows,
        "review_queue_artifact_path": _safe_text(
            operator_decision.get("review_queue_artifact_path")
        ),
        "review_inventory_artifact_path": _safe_text(
            operator_decision.get("review_inventory_artifact_path")
        ),
        "review_decision_artifact_path": _safe_text(
            operator_decision.get("review_decision_artifact_path")
        ),
        "review_queue_artifact_path_safe": _safe_path(
            operator_decision.get("review_queue_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_inventory_artifact_path_safe": _safe_path(
            operator_decision.get("review_inventory_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_decision_artifact_path_safe": _safe_path(
            operator_decision.get("review_decision_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_inventory_checked": bool(
            confirmations.get("review_inventory_checked")
        ),
        "candidate_queue_review_only": bool(
            confirmations.get("candidate_queue_review_only")
        ),
        "human_decision_only": bool(confirmations.get("human_decision_only")),
        "manual_record_required": bool(confirmations.get("manual_record_required")),
        "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_inventory_query": bool(confirmations.get("no_api_inventory_query")),
        "no_api_review_state_update": bool(
            confirmations.get("no_api_review_state_update")
        ),
        "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")),
        "api_execution_allowed": bool(operator_decision.get("api_execution_allowed")),
        "real_write_allowed_by_api": bool(
            operator_decision.get("real_write_allowed_by_api")
        ),
        "api_candidate_review_allowed": bool(
            operator_decision.get("api_candidate_review_allowed")
        ),
        "api_updates_review_state": bool(
            operator_decision.get("api_updates_review_state")
        ),
        "api_writes_match_result": bool(
            operator_decision.get("api_writes_match_result")
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            operator_decision,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_review_decision_side_effects(
            operator_decision
        ),
    }


def build_mcp_fetch_candidate_queue_writer_review_decision_preview(
    *,
    writer_review_inventory_package=None,
    writer_review_inventory_result=None,
    operator_review_decision=None,
    phase=None,
):
    """建立 writer review decision；不執行查詢、寫檔或寫入。"""
    writer_review_inventory_package = _as_dict(writer_review_inventory_package)
    inventory_result_received = bool(
        isinstance(writer_review_inventory_result, dict)
        and writer_review_inventory_result
    )
    decision_valid_object = (
        isinstance(operator_review_decision, dict)
        if operator_review_decision is not None
        else True
    )
    decision_payload = _as_dict(operator_review_decision)
    inventory_received = bool(
        writer_review_inventory_package or inventory_result_received
    )
    inventory_result = (
        _inventory_from_inputs(
            writer_review_inventory_package,
            writer_review_inventory_result,
            phase,
        )
        if inventory_received
        else {}
    )
    payload_received = bool(
        inventory_received or decision_payload or operator_review_decision is not None
    )
    decision_received = bool(decision_payload)
    inventory = _inventory_summary(inventory_result)
    decision = _operator_review_decision_summary(decision_payload)
    gates = build_review_decision_gates(
        inventory_received=inventory_received,
        decision_received=decision_received and decision_valid_object,
        inventory=inventory,
        decision=decision,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    if not decision_valid_object:
        blocked_reasons.append("operator_review_decision_payload_valid_object")
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_review_decision"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_review_decision_preview"
        ),
        "phase": phase,
        "writer_review_decision_payload_received": payload_received,
        "review_decision_payload_received": payload_received,
        "writer_review_inventory_received": inventory_received,
        "operator_review_decision_received": decision_received,
        "operator_review_decision_valid_object": decision_valid_object,
        "writer_review_inventory_accepted": inventory["accepted"],
        "mcp_fetch_candidate_queue_writer_review_decision_accepted": accepted,
        "candidate_queue_writer_review_decision_ready": accepted,
        "ready_for_candidate_queue_human_review": accepted,
        "ready_for_candidate_queue_review_decision_approval": accepted,
        "ready_for_candidate_queue_review_state_writer": False,
        "ready_for_candidate_queue_review_decision_writer_preflight": False,
        "ready_for_api_database_write": False,
        "ready_for_real_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_candidate_queue_review_api_update": False,
        "ready_for_api_review_state_update": False,
        "ready_for_api_match_write": 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_inventory_query_executed": False,
        "api_candidate_review_update_executed": False,
        "api_updates_review_state": False,
        "api_writes_decision_record": False,
        "api_writes_match_result": False,
        "review_decision_query_executed_by_api": False,
        "payload_row_count": decision["decision_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_inventory_summary": inventory,
        "operator_review_decision_summary": decision,
        "decision_rows": decision["decision_rows"],
        "decision_contract": {
            "expected_current_state": "needs_review",
            "allowed_next_states": list(ALLOWED_REVIEW_DECISIONS),
            "manual_decision_required": True,
            "next_gate": "candidate_queue_review_decision_approval",
            "decision_scope": "candidate_queue_review_decision",
            "forbidden_api_actions": [
                "update_review_state",
                "write_match_result",
                "write_decision_record",
                "insert_missing_queue_row",
                "attach_scheduler",
            ],
        },
        "sample_writer_review_decision_package": (
            build_sample_writer_review_decision_package()
        ),
        "next_operator_steps": [
            "Decision 通過後，只代表可進入人工 approval / writer preflight 設計",
            "API/UI 仍不得自動寫 review_state、寫 match result、補 queue row 或讀 token",
            "matched 決策必須保留 exact identity、variant、false-positive 與 overwrite guard",
        ],
        "payload_persisted": False,
        "review_decision_persisted": False,
        "writer_review_decision_persisted": False,
        "candidate_queue_review_decision_persisted": False,
        "candidate_queue_review_decision_file_written": False,
        "review_decision_file_written": False,
        "decision_record_written": False,
        "decision_record_file_written": False,
        "review_queue_file_written": False,
        "candidate_review_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,
    }
