"""候選審核 queue AI summary persistence operator readiness preview。

本模組只檢查 CLI 寫入 metadata_json 前的操作員證據是否齊備；不讀
approval token、不執行 CLI、不開 DB connection、不寫 metadata_json、不派送
Telegram、不掛 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",
}
APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
TARGET_TABLE = "market_alert_review_queue"
TARGET_COLUMN = "metadata_json"
SUMMARY_METADATA_KEY = "ai_summary_review"


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 _has_text(value):
    return bool(isinstance(value, str) and value.strip())


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


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 == 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 _side_effects_clear(*payloads):
    blocked_keys = (
        "ready_for_api_database_write",
        "ready_for_telegram_dispatch",
        "ready_for_scheduler_attach",
        "api_executes_cli",
        "api_executes_llm",
        "api_reads_approval_token",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "summary_persistence_run_readiness_file_written",
        "run_readiness_file_written",
        "summary_persistence_run_package_file_written",
        "run_package_file_written",
        "package_artifact_created",
        "summary_persistence_writer_preflight_file_written",
        "summary_persistence_transaction_file_written",
        "summary_file_written",
        "summary_record_written",
        "summary_persistence_record_written",
        "metadata_patch_written",
        "transaction_file_written",
        "database_connection_opened",
        "database_session_created",
        "explicit_transaction_opened",
        "transaction_opened",
        "transaction_committed",
        "database_write_executed",
        "database_commit_executed",
        "review_state_update_executed",
        "llm_call_executed",
        "ollama_call_executed",
        "gemini_call_executed",
        "telegram_dispatched",
        "external_network_executed",
        "scheduler_attached",
        "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)
    artifact_paths = {
        "ai_summary_persistence_transaction_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_transaction_artifact_path")
            or operator_evidence.get("summary_persistence_transaction_artifact_path")
        ),
        "ai_summary_persistence_writer_preflight_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_writer_preflight_artifact_path")
            or operator_evidence.get("summary_persistence_writer_preflight_artifact_path")
        ),
        "ai_summary_persistence_run_package_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_run_package_artifact_path")
            or operator_evidence.get("summary_persistence_run_package_artifact_path")
        ),
        "metadata_json_backup_artifact_path": _safe_text(
            operator_evidence.get("metadata_json_backup_artifact_path")
            or operator_evidence.get("summary_metadata_backup_artifact_path")
        ),
        "ai_summary_persistence_postwrite_smoke_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_postwrite_smoke_artifact_path")
            or operator_evidence.get("summary_persistence_postwrite_smoke_artifact_path")
        ),
    }
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        **artifact_paths,
        "artifact_path_count": sum(1 for value in artifact_paths.values() if _has_text(value)),
        "operator_confirmed_ai_summary_persistence_run_readiness": bool(
            operator_evidence.get("operator_confirmed_ai_summary_persistence_run_readiness")
            or operator_evidence.get("operator_confirmed_summary_persistence_run_readiness")
        ),
        "operator_confirmed_run_package_artifact_reviewed": bool(
            operator_evidence.get("operator_confirmed_run_package_artifact_reviewed")
            or operator_evidence.get("operator_confirmed_payload_manifest_reviewed")
        ),
        "operator_confirmed_backup_artifact_reviewed": bool(
            operator_evidence.get("operator_confirmed_backup_artifact_reviewed")
        ),
        "operator_confirmed_writer_preflight_reviewed": bool(
            operator_evidence.get("operator_confirmed_writer_preflight_reviewed")
            or operator_evidence.get("operator_confirmed_cli_preflight_reviewed")
        ),
        "operator_confirmed_cli_command_reviewed": bool(
            operator_evidence.get("operator_confirmed_cli_command_reviewed")
        ),
        "operator_confirmed_one_time_token_shell_only": bool(
            operator_evidence.get("operator_confirmed_one_time_token_shell_only")
            or operator_evidence.get("operator_acknowledged_shell_only_token")
        ),
        "operator_confirmed_postwrite_smoke_required": bool(
            operator_evidence.get("operator_confirmed_postwrite_smoke_required")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_telegram_dispatch")
        ),
        "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 _package_summary(run_package):
    run_package = _as_dict(run_package)
    manifest = _as_dict(run_package.get("payload_manifest"))
    commands = [_as_dict(item) for item in _as_list(run_package.get("command_bundle"))]
    required_artifacts = [_as_dict(item) for item in _as_list(run_package.get("required_artifacts"))]
    return {
        "mode": run_package.get("mode"),
        "package_ready": bool(run_package.get("package_ready")),
        "ready_for_summary_persistence_run_readiness": bool(
            run_package.get("ready_for_summary_persistence_run_readiness")
        ),
        "payload_count": int(manifest.get("payload_count") or 0),
        "manifest_hash": manifest.get("manifest_hash"),
        "dedupe_keys": _as_list(manifest.get("dedupe_keys")),
        "summary_payload_hash": manifest.get("summary_payload_hash"),
        "command_count": len(commands),
        "writer_command_present": any(
            command.get("key") == "metadata_json_writer"
            and command.get("executes_database") is True
            and command.get("executed") is False
            for command in commands
        ),
        "commands_executed": any(command.get("executed") for command in commands),
        "required_artifact_count": len(required_artifacts),
        "required_artifact_keys": [item.get("key") for item in required_artifacts],
        "side_effects_clear": _side_effects_clear(run_package),
    }


def _readiness_gates(*, package, operator, apply_real_write):
    return [
        {
            "key": "summary_persistence_run_package_ready",
            "label": "AI summary persistence run package 必須已通過",
            "passed": bool(
                package["mode"]
                == "candidate_queue_review_ai_summary_persistence_run_package_preview"
                and package["package_ready"]
                and package["ready_for_summary_persistence_run_readiness"]
            ),
        },
        {
            "key": "summary_persistence_payload_manifest_small_batch",
            "label": "metadata_json persistence 首次 operator run 必須是 1 到 5 筆小流量",
            "passed": bool(0 < package["payload_count"] <= 5),
        },
        {
            "key": "summary_persistence_command_bundle_ready",
            "label": "run package 必須含 CLI writer 命令，且 API 尚未執行任何命令",
            "passed": bool(
                package["command_count"] >= 5
                and package["writer_command_present"]
                and not package["commands_executed"]
            ),
        },
        {
            "key": "summary_persistence_required_artifacts_recorded",
            "label": "transaction、preflight、run package、metadata backup 與 post-write smoke artifact path 必須齊備",
            "passed": bool(
                operator["ai_summary_persistence_transaction_artifact_path"]
                and operator["ai_summary_persistence_writer_preflight_artifact_path"]
                and operator["ai_summary_persistence_run_package_artifact_path"]
                and operator["metadata_json_backup_artifact_path"]
                and operator["ai_summary_persistence_postwrite_smoke_artifact_path"]
            ),
        },
        {
            "key": "operator_confirmed_summary_persistence_run_readiness",
            "label": "操作員確認 CLI-only、備份、post-write smoke、無 API 寫入與無排程掛載",
            "passed": bool(
                operator["operator_confirmed_ai_summary_persistence_run_readiness"]
                and operator["operator_confirmed_run_package_artifact_reviewed"]
                and operator["operator_confirmed_backup_artifact_reviewed"]
                and operator["operator_confirmed_writer_preflight_reviewed"]
                and operator["operator_confirmed_cli_command_reviewed"]
                and operator["operator_confirmed_one_time_token_shell_only"]
                and operator["operator_confirmed_postwrite_smoke_required"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_telegram_dispatch"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "summary_persistence_run_readiness_no_approval_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator["approval_token_submitted_to_api"],
        },
        {
            "key": "summary_persistence_run_readiness_apply_real_write_not_requested_from_api",
            "label": "API/UI readiness 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
        {
            "key": "summary_persistence_run_readiness_has_no_side_effects",
            "label": "readiness preview 不得開 DB、寫檔、呼叫 LLM、派 Telegram 或掛 scheduler",
            "passed": package["side_effects_clear"],
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_run_readiness(
    *,
    ai_summary_persistence_run_package,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 AI summary persistence operator readiness preview；不執行副作用。"""
    package = _package_summary(ai_summary_persistence_run_package)
    operator = _operator_summary(operator_evidence)
    gates = _readiness_gates(
        package=package,
        operator=operator,
        apply_real_write=bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    run_readiness_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_run_readiness_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "persist_ai_summary_metadata_json",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "run_readiness_ready": run_readiness_ready,
        "summary_persistence_run_readiness_ready": run_readiness_ready,
        "ready_for_cli_operator_run": run_readiness_ready,
        "ready_for_summary_persistence_run_receipt": run_readiness_ready,
        "ready_for_summary_persistence_cli_run": False,
        "ready_for_real_write": False,
        "ready_for_api_database_write": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_scheduler_attach": False,
        "package_artifact_created": False,
        "summary_persistence_run_readiness_file_written": False,
        "run_readiness_file_written": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "transaction_file_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": False,
        "review_state_update_executed": False,
        "read_only_query_executed": False,
        "database_connection_opened": False,
        "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,
        "statement_count": package["payload_count"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "operator_ai_summary_persistence_run_readiness": operator,
        "run_package_summary": package,
        "cli_execution_boundary": {
            "api_may_execute_cli": False,
            "operator_shell_required": True,
            "one_time_token_shell_only": True,
            "requires_metadata_json_backup": True,
            "requires_read_only_preflight": True,
            "requires_postwrite_smoke_after_cli": True,
        },
        "next_operator_steps": [
            "保存 AI summary persistence run package JSON",
            "保存 metadata_json 寫入前備份",
            "保存 CLI read-only preflight 輸出",
            "確認一次性 approval token 只在 CLI shell 注入",
            "CLI 寫入後立即保存 writer output 與 post-write smoke 結果",
        ],
        "safe_boundaries": [
            "do_not_execute_summary_persistence_writer_from_run_readiness_api",
            "do_not_read_approval_token_from_summary_persistence_run_readiness_api",
            "do_not_create_summary_persistence_run_readiness_artifacts_from_api",
            "do_not_open_database_connection_from_summary_persistence_run_readiness",
            "do_not_write_metadata_json_from_summary_persistence_run_readiness",
            "do_not_update_review_state_from_summary_persistence_run_readiness",
            "do_not_dispatch_telegram_from_summary_persistence_run_readiness",
            "do_not_attach_scheduler_from_summary_persistence_run_readiness",
            "future_summary_persistence_write_must_use_cli_only_gate",
            "metadata_json_backup_required_before_summary_persistence_write",
            "summary_persistence_postwrite_smoke_required",
            "ai_summary_persistence_run_readiness_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
