"""候選審核 queue completion archive 預覽。

本模組只整理 review_state closeout / inventory 後的封存摘要；
不讀 approval token、不執行 CLI、不寫檔、不寫 DB、不更新 review_state、
不 commit、不掛 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"


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 _safe_text(value, limit=300):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _side_effects_clear(*payloads):
    blocked_keys = (
        "api_executes_cli",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "archive_file_written",
        "archive_record_written",
        "archive_manifest_written",
        "database_write_executed",
        "database_commit_executed",
        "migration_executed",
        "external_network_executed",
        "scheduler_attached",
        "review_state_update_executed",
        "writes_executed",
        "would_write_database",
    )
    return all(
        not _as_dict(payload).get(key)
        for payload in payloads
        for key in blocked_keys
    )


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_review_completion_archive": bool(
            operator_evidence.get("operator_confirmed_review_completion_archive")
            or operator_evidence.get("operator_confirmed_archive_ready")
        ),
        "operator_confirmed_archive_is_read_only": bool(
            operator_evidence.get("operator_confirmed_archive_is_read_only")
            or operator_evidence.get("operator_confirmed_post_closeout_inventory_read_only")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "review_completion_archive_path": _safe_text(
            operator_evidence.get("review_completion_archive_path")
            or operator_evidence.get("archive_artifact_path")
        ),
        "post_closeout_inventory_artifact_path": _safe_text(
            operator_evidence.get("post_closeout_inventory_artifact_path")
            or operator_evidence.get("inventory_artifact_path")
        ),
        "review_state_closeout_artifact_path": _safe_text(
            operator_evidence.get("review_state_closeout_artifact_path")
            or operator_evidence.get("closeout_artifact_path")
        ),
        "review_state_receipt_artifact_path": _safe_text(
            operator_evidence.get("review_state_receipt_artifact_path")
            or operator_evidence.get("receipt_artifact_path")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _inventory_summary(post_closeout_inventory):
    post_closeout_inventory = _as_dict(post_closeout_inventory)
    return {
        "provided": bool(post_closeout_inventory),
        "mode": post_closeout_inventory.get("mode"),
        "post_closeout_inventory_ready": bool(
            post_closeout_inventory.get("post_closeout_inventory_ready")
        ),
        "ready_for_review_completion_archive": bool(
            post_closeout_inventory.get("ready_for_review_completion_archive")
        ),
        "read_only_query_executed": bool(
            post_closeout_inventory.get("read_only_query_executed")
        ),
        "database_connection_opened": bool(
            post_closeout_inventory.get("database_connection_opened")
        ),
        "database_write_executed": bool(
            post_closeout_inventory.get("database_write_executed")
        ),
        "database_commit_executed": bool(
            post_closeout_inventory.get("database_commit_executed")
        ),
        "review_state_update_executed": bool(
            post_closeout_inventory.get("review_state_update_executed")
        ),
        "scheduler_attached": bool(post_closeout_inventory.get("scheduler_attached")),
        "expected_dedupe_keys": sorted(
            str(key) for key in _as_list(post_closeout_inventory.get("expected_dedupe_keys"))
        ),
        "found_dedupe_keys": sorted(
            str(key) for key in _as_list(post_closeout_inventory.get("found_dedupe_keys"))
        ),
        "missing_dedupe_keys": sorted(
            str(key) for key in _as_list(post_closeout_inventory.get("missing_dedupe_keys"))
        ),
        "state_mismatches": _as_list(post_closeout_inventory.get("state_mismatches")),
        "row_summaries": _as_list(post_closeout_inventory.get("row_summaries")),
        "blocked_reasons": _as_list(post_closeout_inventory.get("blocked_reasons")),
    }


def _transaction_summary(transaction_preview):
    transaction_preview = _as_dict(transaction_preview)
    statements = _as_list(transaction_preview.get("statements"))
    return {
        "mode": transaction_preview.get("mode"),
        "target_table": transaction_preview.get("target_table"),
        "transaction_ready": bool(transaction_preview.get("transaction_ready")),
        "statement_count": len(statements),
        "statement_operations": sorted(
            {
                _as_dict(statement).get("operation")
                for statement in statements
                if _as_dict(statement).get("operation")
            }
        ),
    }


def _artifact_manifest(transaction_preview, run_receipt, run_closeout, inventory, operator):
    rows = inventory["row_summaries"]
    evidence_bundle_ids = sorted(
        {
            str(_as_dict(row).get("evidence_bundle_id"))
            for row in rows
            if _as_dict(row).get("evidence_bundle_id")
        }
    )
    return {
        "target_table": TARGET_TABLE,
        "transaction": _transaction_summary(transaction_preview),
        "receipt": {
            "mode": _as_dict(run_receipt).get("mode"),
            "receipt_passed": bool(_as_dict(run_receipt).get("receipt_passed")),
            "expected_dedupe_key_count": len(_as_list(_as_dict(run_receipt).get("expected_dedupe_keys"))),
        },
        "closeout": {
            "mode": _as_dict(run_closeout).get("mode"),
            "closeout_passed": bool(_as_dict(run_closeout).get("closeout_passed")),
            "ready_for_review_inventory": bool(
                _as_dict(run_closeout).get("ready_for_review_inventory")
            ),
        },
        "inventory": {
            "mode": inventory["mode"],
            "post_closeout_inventory_ready": inventory[
                "post_closeout_inventory_ready"
            ],
            "expected_dedupe_key_count": len(inventory["expected_dedupe_keys"]),
            "found_dedupe_key_count": len(inventory["found_dedupe_keys"]),
            "missing_dedupe_key_count": len(inventory["missing_dedupe_keys"]),
            "row_summary_count": len(rows),
            "state_mismatch_count": len(inventory["state_mismatches"]),
            "evidence_bundle_ids": evidence_bundle_ids,
        },
        "artifact_paths": {
            "review_state_receipt_artifact_path": operator[
                "review_state_receipt_artifact_path"
            ],
            "review_state_closeout_artifact_path": operator[
                "review_state_closeout_artifact_path"
            ],
            "post_closeout_inventory_artifact_path": operator[
                "post_closeout_inventory_artifact_path"
            ],
            "review_completion_archive_path": operator[
                "review_completion_archive_path"
            ],
        },
    }


def _archive_gates(*, inventory, operator, manifest):
    expected_keys = inventory["expected_dedupe_keys"]
    found_keys = inventory["found_dedupe_keys"]
    missing_keys = inventory["missing_dedupe_keys"]
    state_mismatches = inventory["state_mismatches"]
    rows = inventory["row_summaries"]
    artifact_paths = manifest["artifact_paths"]
    return [
        {
            "key": "post_closeout_inventory_preview_provided",
            "label": "必須提供 post-closeout inventory preview",
            "passed": bool(
                inventory["provided"]
                and inventory["mode"]
                == "candidate_queue_review_decision_post_closeout_inventory_preview"
            ),
        },
        {
            "key": "post_closeout_inventory_ready",
            "label": "post-closeout inventory 必須已通過",
            "passed": bool(
                inventory["post_closeout_inventory_ready"]
                and inventory["ready_for_review_completion_archive"]
            ),
        },
        {
            "key": "archive_dedupe_keys_complete",
            "label": "expected / found dedupe key 必須一致且不可缺漏",
            "passed": bool(expected_keys and expected_keys == found_keys and not missing_keys),
        },
        {
            "key": "archive_review_state_rows_present",
            "label": "封存摘要必須包含 review_state row snapshot",
            "passed": bool(rows),
        },
        {
            "key": "archive_review_state_mismatches_absent",
            "label": "封存前不可存在 review_state mismatch",
            "passed": not state_mismatches,
        },
        {
            "key": "operator_confirmed_review_completion_archive",
            "label": "操作員確認本批 review 已可封存",
            "passed": bool(
                operator["operator_confirmed_review_completion_archive"]
                and operator["operator_confirmed_archive_is_read_only"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "archive_artifact_paths_recorded",
            "label": "receipt、closeout、inventory 與 archive artifact path 必須齊備",
            "passed": all(artifact_paths.values()),
        },
        {
            "key": "archive_no_approval_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator["approval_token_submitted_to_api"],
        },
        {
            "key": "archive_preview_has_no_side_effects",
            "label": "archive gate 不得寫檔、寫 DB、更新 review_state 或掛 scheduler",
            "passed": _side_effects_clear(inventory),
        },
    ]


def build_candidate_queue_review_completion_archive(
    *,
    transaction_preview,
    run_receipt,
    run_closeout,
    post_closeout_inventory,
    operator_evidence=None,
    execute_requested=False,
):
    """建立 review completion archive 預覽；不執行任何副作用。"""
    inventory = _inventory_summary(post_closeout_inventory)
    operator = _operator_summary(operator_evidence)
    manifest = _artifact_manifest(
        transaction_preview,
        run_receipt,
        run_closeout,
        inventory,
        operator,
    )
    gates = _archive_gates(
        inventory=inventory,
        operator=operator,
        manifest=manifest,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    archive_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_completion_archive_preview",
        "target_table": TARGET_TABLE,
        "target_operation": "archive_review_completion_evidence",
        "execute_requested": bool(execute_requested),
        "review_completion_archive_ready": archive_ready,
        "archive_manifest_ready": archive_ready,
        "ready_for_next_manual_phase": archive_ready,
        "ready_for_ai_summary_review": archive_ready,
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": 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,
        "archive_file_written": False,
        "archive_record_written": False,
        "archive_manifest_written": False,
        "review_state_update_executed": False,
        "read_only_query_executed": inventory["read_only_query_executed"],
        "database_connection_opened": inventory["database_connection_opened"],
        "database_session_created": False,
        "explicit_transaction_opened": False,
        "transaction_opened": False,
        "transaction_committed": 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,
        "expected_dedupe_keys": inventory["expected_dedupe_keys"],
        "found_dedupe_keys": inventory["found_dedupe_keys"],
        "missing_dedupe_keys": inventory["missing_dedupe_keys"],
        "state_mismatches": inventory["state_mismatches"],
        "row_summary_count": len(inventory["row_summaries"]),
        "archive_manifest": manifest,
        "operator_archive_summary": operator,
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "next_operator_steps": [
            "保存 review_state receipt、closeout、post-closeout inventory artifact",
            "確認 archive manifest 只含摘要與 artifact path，不含 approval token",
            "將本批 dedupe key 與 review_state 結果納入人工封存紀錄",
            "若封存 gate 未通過，回到 post-closeout inventory 或 receipt 修正",
        ],
        "safe_boundaries": [
            "do_not_write_archive_file_from_api",
            "do_not_insert_archive_record_from_api",
            "do_not_update_review_state_from_archive_gate",
            "do_not_read_approval_token_from_archive_gate",
            "do_not_execute_cli_from_archive_gate",
            "do_not_attach_scheduler_from_archive_gate",
            "review_completion_archive_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
