"""市場情報 MCP fetch candidate queue review preview。

本模組只審核 candidate handoff 後的人工 queue review 草案；
不建立 queue、不寫 DB、不讀 artifact、不發 HTTP request、不掛 scheduler。
"""

from services.market_intel.mcp_fetch_candidate_handoff_review import (
    build_mcp_fetch_candidate_handoff_review_preview,
)


MAX_QUEUE_REVIEW_ITEMS = 80
SAFE_REVIEW_STATES = {"needs_review"}
SAFE_REVIEW_MODES = {"operator_queue_review_preview"}
SAFE_TARGET_QUEUES = {"manual_candidate_review"}
SAFE_ALLOWED_ACTIONS = {
    "confirm_campaign_candidate",
    "confirm_product_candidate",
    "reject_candidate",
    "defer_candidate",
}

FORBIDDEN_SECRET_KEYS = (
    "approval_token",
    "approval-token",
    "api_key",
    "authorization",
    "bearer",
    "client_secret",
    "cookie",
    "password",
    "secret",
    "session_cookie",
    "token",
)

SAFE_SECRET_METADATA_KEYS = {
    "operator_confirmed_no_secret_payload",
}

FORBIDDEN_RAW_PAYLOAD_KEYS = (
    "body_html",
    "document_html",
    "html",
    "page_html",
    "raw_body",
    "raw_html",
    "raw_snapshot",
    "response_body",
)

_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_execution",
    "allow_database_write",
    "allow_external_network_in_api",
    "allow_scheduler_attach",
    "api_executed_cli",
    "api_executes_cli",
    "api_executes_docker",
    "api_executes_health_check",
    "api_executes_ssh",
    "api_opens_database_connection",
    "api_uses_external_network",
    "api_writes_database",
    "attach_scheduler",
    "candidate_queue_created",
    "candidate_queue_persisted",
    "candidate_review_state_updated",
    "cli_executed",
    "command_executed",
    "database_commit_executed",
    "database_session_created",
    "database_write_executed",
    "external_network_executed",
    "fetch_executed",
    "file_written",
    "network_request_allowed",
    "payload_persisted",
    "scheduler_attached",
    "write_database",
    "writes_executed",
    "would_write_database",
)


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 _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _has_text(value):
    return bool(isinstance(value, str) and value.strip())


def _safe_text(value, limit=500):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _contains_forbidden_key(value, forbidden_keys, *, safe_keys=None):
    safe_keys = safe_keys or set()
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in safe_keys and isinstance(nested, bool):
                continue
            if any(forbidden_key in normalized_key for forbidden_key in forbidden_keys):
                return True
            if _contains_forbidden_key(nested, forbidden_keys, safe_keys=safe_keys):
                return True
    elif isinstance(value, list):
        return any(
            _contains_forbidden_key(item, forbidden_keys, safe_keys=safe_keys)
            for item in value
        )
    return False


def _blocked_side_effects(payload):
    found = []

    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 _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 found


def _handoff_review_from_inputs(handoff_review_package, handoff_review_result, phase):
    if isinstance(handoff_review_result, dict) and handoff_review_result:
        return handoff_review_result

    handoff_review_package = _as_dict(handoff_review_package)
    return build_mcp_fetch_candidate_handoff_review_preview(
        parser_review_package=(
            handoff_review_package.get("parser_review_package")
            or handoff_review_package.get("parser_review")
            or handoff_review_package.get("result_parser_review")
        ),
        parser_review_result=(
            handoff_review_package.get("parser_review_result")
            or handoff_review_package.get("mcp_fetch_result_parser_review")
        ),
        candidate_handoff=(
            handoff_review_package.get("candidate_handoff")
            or handoff_review_package.get("handoff")
            or handoff_review_package.get("handoff_payload")
        ),
        phase=phase,
    )


def _candidate_key(candidate, candidate_type):
    candidate = _as_dict(candidate)
    if candidate_type == "campaign":
        return candidate.get("campaign_key")
    return candidate.get("platform_product_id")


def _sample_candidate_queue_review_package():
    handoff_preview = build_mcp_fetch_candidate_handoff_review_preview()
    handoff_review_package = handoff_preview["sample_candidate_handoff_package"]
    handoff_review_result = build_mcp_fetch_candidate_handoff_review_preview(
        parser_review_package=handoff_review_package["parser_review_package"],
        parser_review_result=handoff_review_package["parser_review_result"],
        candidate_handoff=handoff_review_package["candidate_handoff"],
    )
    handoff_summary = handoff_review_result["candidate_handoff_summary"]
    review_items = []
    for candidate_type, candidates in (
        ("campaign", handoff_summary.get("campaign_candidates", [])),
        ("product", handoff_summary.get("product_candidates", [])),
    ):
        for item in candidates:
            item = _as_dict(item)
            candidate_key = _candidate_key(item, candidate_type)
            review_items.append(
                {
                    "candidate_type": candidate_type,
                    "platform_code": item.get("platform_code"),
                    "source_key": item.get("source_key"),
                    "candidate_key": candidate_key,
                    "candidate_name": item.get("campaign_name") or item.get("name"),
                    "candidate_url": item.get("campaign_url") or item.get("product_url"),
                    "review_state": "needs_review",
                    "priority_lane": "normal",
                    "allowed_actions": sorted(SAFE_ALLOWED_ACTIONS),
                    "evidence_ref": "parser_summary",
                    "queue_write_status": "not_persisted",
                }
            )

    return {
        "handoff_review_package": handoff_review_package,
        "handoff_review_result": handoff_review_result,
        "candidate_queue_review": {
            "review_id": "market-intel-candidate-queue-review-sample",
            "review_mode": "operator_queue_review_preview",
            "target_queue": "manual_candidate_review",
            "operator_confirmed_no_database_write": True,
            "operator_confirmed_no_external_network": True,
            "operator_confirmed_no_scheduler_attach": True,
            "operator_confirmed_no_persistence": True,
            "operator_confirmed_manual_review_required": True,
            "operator_confirmed_no_secret_payload": True,
            "summary": {
                "campaign_candidate_count": handoff_summary.get(
                    "campaign_candidate_count",
                    0,
                ),
                "product_candidate_count": handoff_summary.get(
                    "product_candidate_count",
                    0,
                ),
                "review_item_count": len(review_items),
            },
            "review_items": review_items,
        },
    }


def _handoff_summary(handoff_review):
    handoff_review = _as_dict(handoff_review)
    side_effects_clear = bool(
        not handoff_review.get("manual_fetch_gate_opened_by_api")
        and not handoff_review.get("network_request_allowed")
        and not handoff_review.get("api_executes_cli")
        and not handoff_review.get("api_opens_database_connection")
        and not handoff_review.get("api_writes_database")
        and not handoff_review.get("api_uses_external_network")
        and not handoff_review.get("database_write_executed")
        and not handoff_review.get("fetch_executed")
        and not handoff_review.get("cli_executed")
        and not handoff_review.get("file_written")
        and not handoff_review.get("scheduler_attached")
        and not handoff_review.get("candidate_queue_created")
        and not handoff_review.get("candidate_queue_persisted")
    )
    summary = _as_dict(handoff_review.get("candidate_handoff_summary"))
    return {
        "mode": handoff_review.get("mode"),
        "accepted": bool(
            handoff_review.get("mcp_fetch_candidate_handoff_review_accepted")
        ),
        "ready_for_manual_candidate_queue_review": bool(
            handoff_review.get("ready_for_manual_candidate_queue_review")
        ),
        "source_count": _safe_int(handoff_review.get("handoff_source_count")),
        "campaign_candidate_count": _safe_int(
            handoff_review.get("campaign_candidate_count")
        ),
        "product_candidate_count": _safe_int(
            handoff_review.get("product_candidate_count")
        ),
        "candidate_count": _safe_int(handoff_review.get("candidate_count")),
        "source_keys": sorted(
            tuple(item)
            for item in _as_list(summary.get("source_keys"))
            if isinstance(item, (list, tuple)) and len(item) == 2
        ),
        "campaign_candidate_keys": sorted(
            key for key in _as_list(summary.get("campaign_candidate_keys")) if key
        ),
        "product_candidate_keys": sorted(
            key for key in _as_list(summary.get("product_candidate_keys")) if key
        ),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": handoff_review.get("blocked_reasons", []),
    }


def _review_item_summary(item):
    item = _as_dict(item)
    allowed_actions = sorted(
        action for action in _as_list(item.get("allowed_actions")) if action
    )
    return {
        "candidate_type": _safe_text(item.get("candidate_type"), 40),
        "platform_code": _safe_text(item.get("platform_code"), 80),
        "source_key": _safe_text(item.get("source_key"), 160),
        "candidate_key": _safe_text(item.get("candidate_key"), 240),
        "candidate_name": _safe_text(item.get("candidate_name"), 300),
        "candidate_url": _safe_text(item.get("candidate_url"), 500),
        "review_state": _safe_text(item.get("review_state"), 80),
        "priority_lane": _safe_text(item.get("priority_lane"), 80),
        "allowed_actions": allowed_actions,
        "evidence_ref": _safe_text(item.get("evidence_ref"), 160),
        "queue_write_status": _safe_text(item.get("queue_write_status"), 80),
        "required_fields_present": bool(
            item.get("candidate_type") in {"campaign", "product"}
            and _has_text(item.get("platform_code"))
            and _has_text(item.get("source_key"))
            and _has_text(item.get("candidate_key"))
            and _has_text(item.get("candidate_name"))
            and _has_text(item.get("candidate_url"))
        ),
        "allowed_actions_safe": bool(
            allowed_actions
            and set(allowed_actions).issubset(SAFE_ALLOWED_ACTIONS)
        ),
    }


def _queue_review_summary(candidate_queue_review):
    candidate_queue_review = _as_dict(candidate_queue_review)
    items = [
        _review_item_summary(item)
        for item in _as_list(candidate_queue_review.get("review_items"))
    ]
    campaign_items = [item for item in items if item["candidate_type"] == "campaign"]
    product_items = [item for item in items if item["candidate_type"] == "product"]
    summary = _as_dict(candidate_queue_review.get("summary"))
    return {
        "provided_keys": sorted(candidate_queue_review.keys()),
        "review_id": _safe_text(candidate_queue_review.get("review_id"), 160),
        "review_mode": _safe_text(candidate_queue_review.get("review_mode"), 120),
        "target_queue": _safe_text(candidate_queue_review.get("target_queue"), 160),
        "operator_confirmed_no_database_write": bool(
            candidate_queue_review.get("operator_confirmed_no_database_write")
        ),
        "operator_confirmed_no_external_network": bool(
            candidate_queue_review.get("operator_confirmed_no_external_network")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            candidate_queue_review.get("operator_confirmed_no_scheduler_attach")
        ),
        "operator_confirmed_no_persistence": bool(
            candidate_queue_review.get("operator_confirmed_no_persistence")
        ),
        "operator_confirmed_manual_review_required": bool(
            candidate_queue_review.get("operator_confirmed_manual_review_required")
        ),
        "operator_confirmed_no_secret_payload": bool(
            candidate_queue_review.get("operator_confirmed_no_secret_payload")
        ),
        "review_item_count": len(items),
        "summary_review_item_count": _safe_int(summary.get("review_item_count")),
        "campaign_candidate_count": len(campaign_items),
        "summary_campaign_candidate_count": _safe_int(
            summary.get("campaign_candidate_count")
        ),
        "product_candidate_count": len(product_items),
        "summary_product_candidate_count": _safe_int(
            summary.get("product_candidate_count")
        ),
        "campaign_candidate_keys": sorted(
            item["candidate_key"] for item in campaign_items if item["candidate_key"]
        ),
        "product_candidate_keys": sorted(
            item["candidate_key"] for item in product_items if item["candidate_key"]
        ),
        "review_items": items,
        "all_review_states_safe": bool(
            items and all(item["review_state"] in SAFE_REVIEW_STATES for item in items)
        ),
        "all_required_fields_present": bool(
            items and all(item["required_fields_present"] for item in items)
        ),
        "all_allowed_actions_safe": bool(
            items and all(item["allowed_actions_safe"] for item in items)
        ),
        "all_queue_write_status_preview": bool(
            items and all(item["queue_write_status"] == "not_persisted" for item in items)
        ),
        "summary_counts_match_items": bool(
            _safe_int(summary.get("review_item_count")) == len(items)
            and _safe_int(summary.get("campaign_candidate_count")) == len(campaign_items)
            and _safe_int(summary.get("product_candidate_count")) == len(product_items)
        ),
        "raw_payload_submitted_to_api": _contains_forbidden_key(
            candidate_queue_review,
            FORBIDDEN_RAW_PAYLOAD_KEYS,
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            candidate_queue_review,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_side_effects(candidate_queue_review),
    }


def _queue_review_gates(
    *,
    handoff_review_received,
    queue_review_payload_received,
    queue_review_valid_object,
    handoff,
    queue_review,
):
    handoff_campaign_keys = set(handoff["campaign_candidate_keys"])
    queue_campaign_keys = set(queue_review["campaign_candidate_keys"])
    handoff_product_keys = set(handoff["product_candidate_keys"])
    queue_product_keys = set(queue_review["product_candidate_keys"])
    operator_boundaries_confirmed = bool(
        queue_review["operator_confirmed_no_database_write"]
        and queue_review["operator_confirmed_no_external_network"]
        and queue_review["operator_confirmed_no_scheduler_attach"]
        and queue_review["operator_confirmed_no_persistence"]
        and queue_review["operator_confirmed_manual_review_required"]
        and queue_review["operator_confirmed_no_secret_payload"]
    )
    return [
        {
            "key": "handoff_review_payload_or_result_received",
            "label": "已提供 candidate handoff review package 或已審核結果",
            "passed": handoff_review_received,
        },
        {
            "key": "handoff_review_accepted",
            "label": "candidate handoff review gate 必須已通過",
            "passed": handoff["accepted"],
        },
        {
            "key": "handoff_ready_for_queue_review",
            "label": "handoff review 只放行到人工 candidate queue review",
            "passed": handoff["ready_for_manual_candidate_queue_review"],
        },
        {
            "key": "handoff_side_effect_free",
            "label": "handoff review 未顯示 API 執行、連外、寫檔、寫 DB 或掛 scheduler",
            "passed": handoff["side_effects_clear"],
        },
        {
            "key": "queue_review_payload_received",
            "label": "已提供 candidate queue review 草案",
            "passed": queue_review_payload_received,
        },
        {
            "key": "queue_review_valid_object",
            "label": "candidate queue review payload 必須是 JSON object",
            "passed": queue_review_valid_object,
        },
        {
            "key": "queue_review_identity_recorded",
            "label": "candidate queue review 必須記錄 review_id",
            "passed": bool(queue_review["review_id"]),
        },
        {
            "key": "queue_review_mode_preview_only",
            "label": "candidate queue review 必須維持 operator_queue_review_preview",
            "passed": queue_review["review_mode"] in SAFE_REVIEW_MODES,
        },
        {
            "key": "queue_review_target_manual_only",
            "label": "target queue 只能是 manual_candidate_review",
            "passed": queue_review["target_queue"] in SAFE_TARGET_QUEUES,
        },
        {
            "key": "queue_review_candidates_match_handoff",
            "label": "queue review 候選 key 必須完全對齊 handoff review",
            "passed": bool(
                handoff_campaign_keys
                and handoff_product_keys
                and queue_campaign_keys == handoff_campaign_keys
                and queue_product_keys == handoff_product_keys
            ),
        },
        {
            "key": "queue_review_item_count_within_limit",
            "label": "queue review item 數需維持小批次上限",
            "passed": bool(0 < queue_review["review_item_count"] <= MAX_QUEUE_REVIEW_ITEMS),
        },
        {
            "key": "queue_review_counts_match_summary",
            "label": "summary count 必須與 review_items 數量一致",
            "passed": queue_review["summary_counts_match_items"],
        },
        {
            "key": "queue_review_required_fields_present",
            "label": "每個 review item 必須具備候選識別欄位",
            "passed": queue_review["all_required_fields_present"],
        },
        {
            "key": "queue_review_state_needs_review_only",
            "label": "review_state 必須停在 needs_review",
            "passed": queue_review["all_review_states_safe"],
        },
        {
            "key": "queue_review_allowed_actions_safe",
            "label": "allowed actions 必須限定人工確認/否決/延後",
            "passed": queue_review["all_allowed_actions_safe"],
        },
        {
            "key": "queue_review_not_persisted",
            "label": "queue_write_status 必須是 not_persisted",
            "passed": queue_review["all_queue_write_status_preview"],
        },
        {
            "key": "queue_review_operator_boundaries_confirmed",
            "label": "操作員確認無寫入、無連外、無排程、無保存且需人工覆核",
            "passed": operator_boundaries_confirmed,
        },
        {
            "key": "queue_review_no_raw_payload",
            "label": "queue review payload 不得回貼 raw HTML/body/snapshot",
            "passed": not queue_review["raw_payload_submitted_to_api"],
        },
        {
            "key": "queue_review_no_secret_or_token_key",
            "label": "queue review payload 不得包含 secret、cookie、password 或 token key",
            "passed": not queue_review["secret_or_token_submitted_to_api"],
        },
        {
            "key": "queue_review_side_effect_free",
            "label": "queue review payload 不得要求 API 執行、連外、寫檔、寫 DB 或掛 scheduler",
            "passed": not queue_review["blocked_side_effects"],
        },
    ]


def build_mcp_fetch_candidate_queue_review_preview(
    *,
    handoff_review_package=None,
    handoff_review_result=None,
    candidate_queue_review=None,
    phase=None,
):
    """建立 fetch candidate queue review；不建立 queue 或寫入。"""
    handoff_review_package = _as_dict(handoff_review_package)
    handoff_review_result_received = bool(
        isinstance(handoff_review_result, dict) and handoff_review_result
    )
    queue_review_valid_object = isinstance(candidate_queue_review, dict) if (
        candidate_queue_review is not None
    ) else True
    queue_review_payload = _as_dict(candidate_queue_review)
    handoff_review = _handoff_review_from_inputs(
        handoff_review_package,
        handoff_review_result,
        phase,
    )
    handoff_review_received = bool(
        handoff_review_package or handoff_review_result_received
    )
    payload_received = bool(
        handoff_review_received
        or queue_review_payload
        or candidate_queue_review is not None
    )
    queue_review_payload_received = bool(queue_review_payload)
    handoff = _handoff_summary(handoff_review)
    queue_review = _queue_review_summary(queue_review_payload)
    gates = _queue_review_gates(
        handoff_review_received=handoff_review_received,
        queue_review_payload_received=queue_review_payload_received,
        queue_review_valid_object=queue_review_valid_object,
        handoff=handoff,
        queue_review=queue_review,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_review"
            if payload_received
            else "mcp_fetch_candidate_queue_review_preview"
        ),
        "phase": phase,
        "candidate_queue_review_payload_received": payload_received,
        "handoff_review_received": handoff_review_received,
        "queue_review_payload_received": queue_review_payload_received,
        "queue_review_valid_object": queue_review_valid_object,
        "handoff_review_accepted": handoff["accepted"],
        "mcp_fetch_candidate_queue_review_accepted": accepted,
        "candidate_queue_review_ready": accepted,
        "ready_for_candidate_queue_writer_preflight": accepted,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "network_request_allowed": False,
        "fetch_executed": False,
        "cli_executed": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "candidate_review_state_updated": False,
        "handoff_source_count": handoff["source_count"],
        "review_item_count": queue_review["review_item_count"],
        "campaign_candidate_count": queue_review["campaign_candidate_count"],
        "product_candidate_count": queue_review["product_candidate_count"],
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "handoff_review_summary": handoff,
        "candidate_queue_review_summary": queue_review,
        "sample_candidate_queue_review_package": (
            _sample_candidate_queue_review_package()
        ),
        "next_operator_steps": [
            "queue review 通過後，只代表可進 writer preflight，不代表可寫 market_*",
            "candidate queue writer、DB import、scheduler attach、AI/Telegram 摘要都必須另開獨立 gate",
            "API/UI 仍不得建立 queue、不得讀 artifact、不得抓外站、不得寫 DB、不得掛 scheduler",
        ],
        "payload_persisted": False,
        "api_executes_health_check": False,
        "api_executes_docker": False,
        "api_executes_ssh": False,
        "api_executes_cli": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_uses_external_network": False,
        "database_session_created": False,
        "database_commit_executed": False,
        "database_write_executed": False,
        "external_network_executed": False,
        "file_written": False,
        "writes_executed": False,
        "would_write_database": False,
        "scheduler_attached": False,
    }
