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

本模組只審核 CLI 寫入 metadata_json 後由操作員貼回的 writer output 與
post-write smoke 結果；不讀 approval token、不執行 CLI、不開 DB
connection、不寫 metadata_json、不更新 review_state、不派送 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",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
EXPECTED_WRITER_MODE = "candidate_queue_review_ai_summary_persistence_writer_cli_executed"
EXPECTED_SMOKE_MODE = (
    "candidate_queue_review_ai_summary_persistence_postwrite_smoke_read_only"
)
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 _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


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


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


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 _keys_match_expected(expected_keys, observed_keys):
    if not expected_keys:
        return False
    return set(expected_keys).issubset(set(observed_keys))


def _hash_matches_expected(expected_hash, observed_hash):
    return bool(expected_hash and observed_hash and str(expected_hash) == str(observed_hash))


def _run_readiness_summary(run_readiness):
    run_readiness = _as_dict(run_readiness)
    package = _as_dict(run_readiness.get("run_package_summary"))
    dedupe_keys = sorted(set(str(key) for key in _as_list(package.get("dedupe_keys")) if key))
    return {
        "provided": bool(run_readiness),
        "mode": run_readiness.get("mode"),
        "run_readiness_ready": bool(run_readiness.get("run_readiness_ready")),
        "ready_for_cli_operator_run": bool(
            run_readiness.get("ready_for_cli_operator_run")
        ),
        "ready_for_summary_persistence_run_receipt": bool(
            run_readiness.get("ready_for_summary_persistence_run_receipt")
        ),
        "statement_count": _safe_int(run_readiness.get("statement_count")),
        "expected_dedupe_keys": dedupe_keys,
        "expected_summary_payload_hash": package.get("summary_payload_hash"),
        "package_ready": bool(package.get("package_ready")),
        "payload_count": _safe_int(package.get("payload_count")),
        "writer_command_present": bool(package.get("writer_command_present")),
        "commands_executed": bool(package.get("commands_executed")),
        "side_effects_clear": bool(package.get("side_effects_clear")),
        "blocked_reasons": _as_list(run_readiness.get("blocked_reasons")),
    }


def _keys_from_writer_output(writer_output):
    writer_output = _as_dict(writer_output)
    execution_result = _as_dict(writer_output.get("execution_result"))
    affected = (
        writer_output.get("affected_dedupe_keys")
        or writer_output.get("updated_dedupe_keys")
        or execution_result.get("affected_dedupe_keys")
        or execution_result.get("updated_dedupe_keys")
        or []
    )
    skipped = (
        writer_output.get("skipped_dedupe_keys")
        or execution_result.get("skipped_dedupe_keys")
        or []
    )
    return {
        "affected": sorted(set(str(key) for key in _as_list(affected) if key)),
        "skipped": sorted(set(str(key) for key in _as_list(skipped) if key)),
    }


def _operator_evidence_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "writer_output_json_path_recorded": _has_text(
            operator_evidence.get("ai_summary_persistence_writer_output_artifact_path")
            or operator_evidence.get("summary_persistence_writer_output_artifact_path")
            or operator_evidence.get("writer_output_json_path")
        ),
        "postwrite_smoke_json_path_recorded": _has_text(
            operator_evidence.get("ai_summary_persistence_postwrite_smoke_artifact_path")
            or operator_evidence.get("summary_persistence_postwrite_smoke_artifact_path")
            or operator_evidence.get("postwrite_smoke_json_path")
        ),
        "metadata_json_backup_artifact_path_recorded": _has_text(
            operator_evidence.get("metadata_json_backup_artifact_path")
            or operator_evidence.get("summary_metadata_backup_artifact_path")
        ),
        "operator_confirmed_no_token_in_artifacts": bool(
            operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "receipt_notes_recorded": _has_text(operator_evidence.get("receipt_notes")),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _writer_summary(writer_output, expected_keys, expected_hash):
    writer_output = _as_dict(writer_output)
    execution_result = _as_dict(writer_output.get("execution_result"))
    writer_keys = _keys_from_writer_output(writer_output)
    observed_keys = sorted(set(writer_keys["affected"] + writer_keys["skipped"]))
    observed_hash = (
        writer_output.get("summary_payload_hash")
        or writer_output.get("payload_hash")
        or execution_result.get("summary_payload_hash")
        or execution_result.get("payload_hash")
    )
    return {
        "provided": bool(writer_output),
        "mode": writer_output.get("mode"),
        "exit_code": writer_output.get("exit_code"),
        "writes_executed": bool(writer_output.get("writes_executed")),
        "would_write_database": bool(writer_output.get("would_write_database")),
        "database_connection_opened": bool(
            writer_output.get("database_connection_opened")
        ),
        "explicit_transaction_opened": bool(
            writer_output.get("explicit_transaction_opened")
        ),
        "database_write_executed": bool(writer_output.get("database_write_executed")),
        "database_commit_executed": bool(writer_output.get("database_commit_executed")),
        "database_rollback_executed": bool(
            writer_output.get("database_rollback_executed")
        ),
        "external_network_executed": bool(writer_output.get("external_network_executed")),
        "scheduler_attached": bool(writer_output.get("scheduler_attached")),
        "api_updates_review_state": bool(writer_output.get("api_updates_review_state")),
        "review_state_update_executed": bool(
            writer_output.get("review_state_update_executed")
        ),
        "metadata_json_update_executed": bool(
            writer_output.get("metadata_json_update_executed")
            or writer_output.get("summary_persistence_record_written")
            or writer_output.get("metadata_patch_written")
            or writer_output.get("database_write_executed")
        ),
        "updated_count": _safe_int(
            writer_output.get("updated_count")
            or writer_output.get("affected_count")
            or writer_output.get("inserted_count")
        ),
        "skipped_count": _safe_int(writer_output.get("skipped_count")),
        "affected_dedupe_keys": writer_keys["affected"],
        "skipped_dedupe_keys": writer_keys["skipped"],
        "observed_dedupe_keys": observed_keys,
        "dedupe_keys_match_expected": _keys_match_expected(expected_keys, observed_keys),
        "expected_summary_payload_hash": expected_hash,
        "summary_payload_hash": observed_hash,
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            expected_hash,
            observed_hash,
        ),
        "approval_token_key_detected": _contains_forbidden_token_key(writer_output),
    }


def _smoke_summary(postwrite_smoke_result, expected_keys, expected_hash):
    postwrite_smoke_result = _as_dict(postwrite_smoke_result)
    found_keys = sorted(
        set(
            str(key)
            for key in _as_list(
                postwrite_smoke_result.get("found_dedupe_keys")
                or postwrite_smoke_result.get("verified_dedupe_keys")
            )
            if key
        )
    )
    missing_keys = sorted(
        set(
            str(key)
            for key in _as_list(postwrite_smoke_result.get("missing_dedupe_keys"))
            if key
        )
    )
    observed_hash = (
        postwrite_smoke_result.get("summary_payload_hash")
        or postwrite_smoke_result.get("observed_summary_payload_hash")
        or postwrite_smoke_result.get("payload_hash")
    )
    return {
        "provided": bool(postwrite_smoke_result),
        "mode": postwrite_smoke_result.get("mode"),
        "postwrite_smoke_passed": bool(
            postwrite_smoke_result.get("postwrite_smoke_passed")
        ),
        "metadata_json_update_verified": bool(
            postwrite_smoke_result.get("metadata_json_update_verified")
            or postwrite_smoke_result.get("ai_summary_review_verified")
            or postwrite_smoke_result.get("summary_persistence_verified")
        ),
        "ready_for_operator_review": bool(
            postwrite_smoke_result.get("ready_for_operator_review")
        ),
        "read_only_query_executed": bool(
            postwrite_smoke_result.get("read_only_query_executed")
        ),
        "database_connection_opened": bool(
            postwrite_smoke_result.get("database_connection_opened")
        ),
        "database_write_executed": bool(
            postwrite_smoke_result.get("database_write_executed")
        ),
        "database_commit_executed": bool(
            postwrite_smoke_result.get("database_commit_executed")
        ),
        "external_network_executed": bool(
            postwrite_smoke_result.get("external_network_executed")
        ),
        "scheduler_attached": bool(postwrite_smoke_result.get("scheduler_attached")),
        "expected_dedupe_key_count": _safe_int(
            postwrite_smoke_result.get("expected_dedupe_key_count")
        ),
        "found_count": _safe_int(postwrite_smoke_result.get("found_count")),
        "missing_count": _safe_int(postwrite_smoke_result.get("missing_count")),
        "found_dedupe_keys": found_keys,
        "missing_dedupe_keys": missing_keys,
        "dedupe_keys_match_expected": _keys_match_expected(expected_keys, found_keys)
        and not missing_keys,
        "expected_summary_payload_hash": expected_hash,
        "summary_payload_hash": observed_hash,
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            expected_hash,
            observed_hash,
        ),
        "approval_token_key_detected": _contains_forbidden_token_key(
            postwrite_smoke_result
        ),
    }


def _receipt_gates(
    *,
    run_readiness,
    writer_summary,
    smoke_summary,
    evidence_summary,
    apply_real_write,
):
    expected_keys = run_readiness["expected_dedupe_keys"]
    return [
        {
            "key": "run_readiness_passed_before_cli",
            "label": "CLI 寫入前 AI summary persistence run readiness 必須已通過",
            "passed": bool(
                run_readiness["mode"]
                == "candidate_queue_review_ai_summary_persistence_run_readiness_preview"
                and run_readiness["ready_for_cli_operator_run"]
                and run_readiness["ready_for_summary_persistence_run_receipt"]
            ),
        },
        {
            "key": "expected_dedupe_keys_present",
            "label": "run package manifest 必須有 dedupe key",
            "passed": bool(expected_keys),
        },
        {
            "key": "writer_output_provided",
            "label": "操作員需貼回 metadata_json CLI writer output",
            "passed": writer_summary["provided"],
        },
        {
            "key": "writer_output_executed_and_committed",
            "label": "writer output 必須顯示 CLI 已寫入 metadata_json 並 commit",
            "passed": bool(
                writer_summary["mode"] == EXPECTED_WRITER_MODE
                and writer_summary["exit_code"] == 0
                and writer_summary["writes_executed"]
                and writer_summary["metadata_json_update_executed"]
                and writer_summary["database_write_executed"]
                and writer_summary["database_commit_executed"]
            ),
        },
        {
            "key": "writer_output_dedupe_keys_match_expected",
            "label": "writer output 的 affected/skipped dedupe key 必須符合 run package",
            "passed": writer_summary["dedupe_keys_match_expected"],
        },
        {
            "key": "writer_output_summary_hash_matches_expected",
            "label": "writer output 的 summary payload hash 必須符合 run package",
            "passed": writer_summary["summary_payload_hash_matches_expected"],
        },
        {
            "key": "writer_output_safe_runtime_boundaries",
            "label": "writer output 不得顯示 scheduler、外部網路、review_state 更新或 rollback error",
            "passed": bool(
                not writer_summary["scheduler_attached"]
                and not writer_summary["external_network_executed"]
                and not writer_summary["database_rollback_executed"]
                and not writer_summary["api_updates_review_state"]
                and not writer_summary["review_state_update_executed"]
            ),
        },
        {
            "key": "writer_output_no_approval_token_key",
            "label": "writer output 不得包含 approval token key",
            "passed": not writer_summary["approval_token_key_detected"],
        },
        {
            "key": "postwrite_smoke_result_provided",
            "label": "操作員需貼回 metadata_json post-write smoke 結果",
            "passed": smoke_summary["provided"],
        },
        {
            "key": "postwrite_smoke_read_only_and_passed",
            "label": "post-write smoke 必須是只讀查詢且驗證 metadata_json.ai_summary_review",
            "passed": bool(
                smoke_summary["mode"] == EXPECTED_SMOKE_MODE
                and smoke_summary["read_only_query_executed"]
                and smoke_summary["postwrite_smoke_passed"]
                and smoke_summary["metadata_json_update_verified"]
            ),
        },
        {
            "key": "postwrite_smoke_dedupe_keys_match_expected",
            "label": "post-write smoke 找到的 queue row 必須符合 run package",
            "passed": smoke_summary["dedupe_keys_match_expected"],
        },
        {
            "key": "postwrite_smoke_summary_hash_matches_expected",
            "label": "post-write smoke 的 summary payload hash 必須符合 run package",
            "passed": smoke_summary["summary_payload_hash_matches_expected"],
        },
        {
            "key": "postwrite_smoke_no_database_write",
            "label": "post-write smoke 不得寫 DB 或 commit",
            "passed": bool(
                not smoke_summary["database_write_executed"]
                and not smoke_summary["database_commit_executed"]
            ),
        },
        {
            "key": "postwrite_smoke_no_approval_token_key",
            "label": "post-write smoke 結果不得包含 approval token key",
            "passed": not smoke_summary["approval_token_key_detected"],
        },
        {
            "key": "operator_receipt_artifacts_recorded",
            "label": "操作員需記錄 writer output、post-write smoke 與 metadata backup artifact",
            "passed": bool(
                evidence_summary["writer_output_json_path_recorded"]
                and evidence_summary["postwrite_smoke_json_path_recorded"]
                and evidence_summary["metadata_json_backup_artifact_path_recorded"]
            ),
        },
        {
            "key": "operator_confirmed_no_token_in_artifacts",
            "label": "操作員確認 artifact 不含一次性 token",
            "passed": bool(
                evidence_summary["operator_confirmed_no_token_in_artifacts"]
                and not evidence_summary["approval_token_submitted_to_api"]
            ),
        },
        {
            "key": "run_receipt_no_approval_token_submitted_to_api",
            "label": "receipt payload 不得包含一次性 approval token key",
            "passed": not evidence_summary["approval_token_submitted_to_api"],
        },
        {
            "key": "run_receipt_apply_real_write_not_requested_from_api",
            "label": "API/UI receipt 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_run_receipt(
    *,
    ai_summary_persistence_run_readiness,
    writer_output=None,
    postwrite_smoke_result=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 AI summary persistence CLI 寫入後 receipt review；不執行副作用。"""
    run_readiness = _run_readiness_summary(ai_summary_persistence_run_readiness)
    expected_keys = run_readiness["expected_dedupe_keys"]
    expected_hash = run_readiness["expected_summary_payload_hash"]
    operator_evidence = _as_dict(operator_evidence)
    evidence_summary = _operator_evidence_summary(operator_evidence)
    writer = _writer_summary(writer_output, expected_keys, expected_hash)
    smoke = _smoke_summary(postwrite_smoke_result, expected_keys, expected_hash)
    gates = _receipt_gates(
        run_readiness=run_readiness,
        writer_summary=writer,
        smoke_summary=smoke,
        evidence_summary=evidence_summary,
        apply_real_write=bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    receipt_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_run_receipt_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),
        "receipt_reviewed": True,
        "run_receipt_passed": receipt_passed,
        "summary_persistence_run_receipt_passed": receipt_passed,
        "ready_for_summary_persistence_closeout": receipt_passed,
        "ready_for_next_manual_phase": receipt_passed,
        "ready_for_summary_persistence_cli_run": False,
        "ready_for_summary_persistence_postwrite_smoke": False,
        "ready_for_real_write": False,
        "ready_for_api_database_write": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_scheduler_attach": 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_persistence_run_receipt_file_written": False,
        "run_receipt_file_written": False,
        "receipt_file_written": 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": len(expected_keys),
        "expected_dedupe_keys": expected_keys,
        "expected_summary_payload_hash": _safe_text(expected_hash, 80),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "run_readiness_summary": run_readiness,
        "operator_evidence_summary": evidence_summary,
        "writer_output_summary": writer,
        "postwrite_smoke_summary": smoke,
        "next_operator_steps": [
            "保存 metadata_json writer output 與 post-write smoke artifact",
            "人工確認每個 dedupe_key 的 metadata_json.ai_summary_review 已符合 summary payload hash",
            "只在 receipt 通過後才進入 summary persistence closeout 與 Telegram dispatch gate",
            "不得從 UI/API 補寫 metadata_json、重跑 CLI、派送 Telegram 或自動掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_execute_summary_persistence_writer_from_receipt_api",
            "do_not_read_approval_token_from_summary_persistence_receipt_api",
            "do_not_echo_operator_receipt_payload",
            "do_not_create_summary_persistence_receipt_artifact_from_api",
            "do_not_open_database_connection_from_summary_persistence_receipt",
            "do_not_write_metadata_json_from_summary_persistence_receipt",
            "do_not_update_review_state_from_summary_persistence_receipt",
            "do_not_commit_summary_persistence_receipt",
            "do_not_dispatch_telegram_from_summary_persistence_receipt",
            "do_not_attach_scheduler_from_summary_persistence_receipt",
            "future_summary_persistence_closeout_must_use_separate_gate",
            "ai_summary_persistence_run_receipt_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
