"""候選審核 queue AI summary Telegram dispatch report run receipt preview。

本模組只審核人工或獨立 job 產出的市場情報 report receipt；不讀 approval
或 Telegram token、不呼叫 LLM、不產報表、不派送 Telegram、不開 DB、不寫檔、
不更新 review_state、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-token",
    "telegram_token",
    "bot_token",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
    "telegram_token_present",
    "telegram_token_configured",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
EXPECTED_RECEIPT_MODES = {
    "market_intel_report_generation_manual_receipt",
    "market_intel_telegram_dispatch_audit_report_receipt",
    "manual_market_intel_report_run_receipt",
    "telegram_dispatch_audit_report_manual_receipt",
}
REQUIRED_REPORT_SECTIONS = {
    "executive_context",
    "telegram_message_evidence",
    "dispatch_audit_evidence",
    "artifact_traceability",
    "runtime_safety",
}
TARGET_TABLE = "market_alert_review_queue"
TARGET_COLUMN = "metadata_json"
SUMMARY_METADATA_KEY = "ai_summary_review"
SIDE_EFFECT_CLEAR_KEYS = (
    "ready_for_report_generation",
    "ready_for_telegram_dispatch",
    "ready_for_api_database_write",
    "ready_for_scheduler_attach",
    "ready_for_llm_call",
    "api_executes_cli",
    "api_executes_llm",
    "api_dispatches_telegram",
    "api_reads_approval_token",
    "api_writes_file",
    "api_writes_database",
    "api_updates_review_state",
    "telegram_dispatch_report_run_receipt_file_written",
    "report_run_receipt_file_written",
    "report_receipt_file_written",
    "report_output_file_written",
    "report_file_written",
    "report_record_written",
    "report_manifest_written",
    "summary_file_written",
    "summary_record_written",
    "summary_manifest_written",
    "ai_summary_generated",
    "llm_call_executed",
    "ollama_call_executed",
    "gemini_call_executed",
    "telegram_dispatched",
    "telegram_dispatch_attempted",
    "external_network_executed",
    "database_connection_opened",
    "database_write_executed",
    "database_commit_executed",
    "review_state_update_executed",
    "scheduler_attached",
    "writes_executed",
    "would_write_database",
)
RESPONSE_FALSE_KEYS = SIDE_EFFECT_CLEAR_KEYS + (
    "ready_for_manual_report_generation",
    "ready_for_ai_summary_generation",
    "ready_for_manual_telegram_dispatch",
    "ready_for_real_write",
    "summary_persistence_record_written",
    "metadata_patch_written",
    "read_only_query_executed",
    "database_session_created",
    "explicit_transaction_opened",
    "transaction_opened",
    "transaction_committed",
    "database_rollback_executed",
)


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 _hash_matches_expected(expected_hash, observed_hash):
    return bool(expected_hash and observed_hash and str(expected_hash) == str(observed_hash))


def _extract_section_keys(value):
    keys = []
    for item in _as_list(value):
        if isinstance(item, dict):
            key = item.get("key") or item.get("section") or item.get("name")
        else:
            key = item
        text = _safe_text(key, 120)
        if text:
            keys.append(text)
    return sorted(set(keys))


def _side_effects_clear(*payloads):
    return all(
        not _as_dict(payload).get(key)
        for payload in payloads
        for key in SIDE_EFFECT_CLEAR_KEYS
    )


def _readiness_summary(report_run_readiness):
    readiness = _as_dict(report_run_readiness)
    manifest = _as_dict(readiness.get("report_generation_readiness_manifest"))
    command = _as_dict(manifest.get("manual_generation_command"))
    boundaries = _as_dict(manifest.get("execution_boundaries"))
    evidence_refs = _as_dict(manifest.get("evidence_refs"))
    return {
        "provided": bool(readiness),
        "mode": readiness.get("mode"),
        "telegram_dispatch_report_run_readiness_ready": bool(
            readiness.get("telegram_dispatch_report_run_readiness_ready")
        ),
        "report_run_readiness_ready": bool(readiness.get("report_run_readiness_ready")),
        "ready_for_market_intel_report_run_receipt": bool(
            readiness.get("ready_for_market_intel_report_run_receipt")
        ),
        "ready_for_manual_report_generation": bool(
            readiness.get("ready_for_manual_report_generation")
        ),
        "ready_for_report_generation": bool(readiness.get("ready_for_report_generation")),
        "statement_count": _safe_int(readiness.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            readiness.get("expected_summary_payload_hash")
            or manifest.get("expected_summary_payload_hash"),
            80,
        ),
        "manifest_version": manifest.get("manifest_version"),
        "source_contract_version": manifest.get("source_contract_version"),
        "target_report_family": manifest.get("target_report_family"),
        "language": manifest.get("language"),
        "intended_report_artifacts": _as_list(manifest.get("intended_report_artifacts")),
        "required_package_sections": _as_list(manifest.get("required_package_sections")),
        "manual_generation_command_present": bool(command.get("key")),
        "manual_generation_executed_by_api": bool(command.get("executed_by_api")),
        "manual_generation_executes_database": bool(command.get("executes_database")),
        "manual_generation_executes_telegram": bool(command.get("executes_telegram")),
        "execution_boundaries": boundaries,
        "evidence_refs": {
            "message_id": _safe_text(evidence_refs.get("message_id"), 120),
            "chat_id": _safe_text(evidence_refs.get("chat_id"), 120),
            "telegram_channel_label": _safe_text(
                evidence_refs.get("telegram_channel_label"),
                180,
            ),
            "summary_payload_hash": _safe_text(
                evidence_refs.get("summary_payload_hash"),
                80,
            ),
        },
        "blocked_reasons": _as_list(readiness.get("blocked_reasons")),
        "side_effects_clear": _side_effects_clear(readiness),
    }


def _receipt_payload(operator_evidence, report_run_receipt):
    operator_evidence = _as_dict(operator_evidence)
    embedded = _as_dict(
        operator_evidence.get("market_intel_report_run_receipt")
        or operator_evidence.get("telegram_dispatch_report_run_receipt")
        or operator_evidence.get("report_generation_receipt")
        or operator_evidence.get("report_run_receipt")
    )
    return _as_dict(report_run_receipt) or embedded


def _receipt_summary(receipt_payload, readiness):
    receipt = _as_dict(receipt_payload)
    artifact = _as_dict(receipt.get("artifact") or receipt.get("report_artifact"))
    boundaries = _as_dict(receipt.get("execution_boundaries"))
    section_keys = _extract_section_keys(
        receipt.get("section_keys")
        or receipt.get("report_sections")
        or artifact.get("section_keys")
    )
    observed_summary_hash = (
        receipt.get("summary_payload_hash")
        or receipt.get("expected_summary_payload_hash")
        or artifact.get("summary_payload_hash")
    )
    report_hash = (
        receipt.get("report_output_hash")
        or receipt.get("report_hash")
        or receipt.get("artifact_hash")
        or artifact.get("sha256")
        or artifact.get("hash")
    )
    report_path = (
        receipt.get("report_output_artifact_path")
        or receipt.get("report_artifact_path")
        or artifact.get("path")
    )
    return {
        "provided": bool(receipt),
        "mode": receipt.get("mode"),
        "report_generated": bool(
            receipt.get("report_generated")
            or receipt.get("generation_success")
            or receipt.get("ok")
            or receipt.get("success")
        ),
        "target_report_family": _safe_text(
            receipt.get("target_report_family")
            or artifact.get("target_report_family"),
            180,
        ),
        "language": _safe_text(receipt.get("language") or artifact.get("language"), 40),
        "report_output_artifact_path": _safe_text(report_path),
        "report_output_hash": _safe_text(report_hash, 120),
        "report_format": _safe_text(
            receipt.get("report_format") or artifact.get("format"),
            40,
        ),
        "generated_at": _safe_text(
            receipt.get("generated_at")
            or receipt.get("created_at")
            or artifact.get("created_at"),
            120,
        ),
        "summary_payload_hash": _safe_text(observed_summary_hash, 80),
        "expected_summary_payload_hash": readiness["expected_summary_payload_hash"],
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            readiness["expected_summary_payload_hash"],
            observed_summary_hash,
        ),
        "section_keys": section_keys,
        "required_report_sections": sorted(REQUIRED_REPORT_SECTIONS),
        "required_report_sections_present": REQUIRED_REPORT_SECTIONS.issubset(
            set(section_keys)
        ),
        "source_readiness_manifest_version": _safe_text(
            receipt.get("source_readiness_manifest_version")
            or receipt.get("manifest_version"),
            120,
        ),
        "generated_by_api": bool(
            receipt.get("generated_by_api")
            or receipt.get("api_generated_report")
            or boundaries.get("api_generates_report")
        ),
        "api_writes_file": bool(receipt.get("api_writes_file") or boundaries.get("api_writes_file")),
        "api_calls_llm": bool(receipt.get("api_calls_llm") or boundaries.get("api_calls_llm")),
        "api_dispatches_telegram": bool(
            receipt.get("api_dispatches_telegram")
            or boundaries.get("api_dispatches_telegram")
        ),
        "api_writes_database": bool(
            receipt.get("api_writes_database") or boundaries.get("api_writes_database")
        ),
        "database_write_executed": bool(receipt.get("database_write_executed")),
        "database_commit_executed": bool(receipt.get("database_commit_executed")),
        "telegram_dispatched": bool(receipt.get("telegram_dispatched")),
        "telegram_dispatch_attempted": bool(receipt.get("telegram_dispatch_attempted")),
        "llm_call_executed": bool(receipt.get("llm_call_executed")),
        "external_network_executed": bool(receipt.get("external_network_executed")),
        "scheduler_attached": bool(receipt.get("scheduler_attached")),
        "review_state_update_executed": bool(
            receipt.get("review_state_update_executed")
        ),
        "approval_or_telegram_token_key_detected": _contains_forbidden_token_key(receipt),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "telegram_dispatch_report_run_package_artifact_path_recorded": _has_text(
            operator_evidence.get("telegram_dispatch_report_run_package_artifact_path")
            or operator_evidence.get("report_run_package_artifact_path")
        ),
        "telegram_dispatch_report_run_readiness_artifact_path_recorded": _has_text(
            operator_evidence.get("telegram_dispatch_report_run_readiness_artifact_path")
            or operator_evidence.get("report_run_readiness_artifact_path")
        ),
        "report_output_artifact_path_recorded": _has_text(
            operator_evidence.get("report_output_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_output_artifact_path")
        ),
        "report_run_receipt_artifact_path_recorded": _has_text(
            operator_evidence.get("report_run_receipt_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_run_receipt_artifact_path"
            )
        ),
        "operator_confirmed_report_run_receipt": bool(
            operator_evidence.get("operator_confirmed_report_run_receipt")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_run_receipt"
            )
        ),
        "operator_confirmed_report_output_hash_matched": bool(
            operator_evidence.get("operator_confirmed_report_output_hash_matched")
            or operator_evidence.get("operator_confirmed_summary_hash_matched")
        ),
        "operator_confirmed_report_sections_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_sections_reviewed")
        ),
        "operator_confirmed_no_token_in_report_receipt": bool(
            operator_evidence.get("operator_confirmed_no_token_in_report_receipt")
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "operator_confirmed_no_api_report_generation": bool(
            operator_evidence.get("operator_confirmed_no_api_report_generation")
            or operator_evidence.get("operator_confirmed_no_api_report_write")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "receipt_notes_recorded": _has_text(
            operator_evidence.get("report_run_receipt_notes")
            or operator_evidence.get("receipt_notes")
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _receipt_gates(*, readiness, receipt, operator, apply_real_write):
    boundaries = readiness["execution_boundaries"]
    return [
        {
            "key": "report_run_readiness_passed_before_manual_report_generation",
            "label": "report run readiness 必須先通過並放行到 receipt",
            "passed": bool(
                readiness["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_run_readiness_preview"
                and readiness["telegram_dispatch_report_run_readiness_ready"]
                and readiness["report_run_readiness_ready"]
                and readiness["ready_for_market_intel_report_run_receipt"]
                and readiness["ready_for_manual_report_generation"]
                and not readiness["ready_for_report_generation"]
            ),
        },
        {
            "key": "report_run_readiness_manifest_complete",
            "label": "readiness manifest 必須完整且確認 API 不產報表、不寫 DB、不派送 Telegram",
            "passed": bool(
                readiness["manifest_version"] == "market_intel_report_run_readiness_v1"
                and readiness["target_report_family"]
                and readiness["language"] == "zh-TW"
                and readiness["expected_summary_payload_hash"]
                and readiness["manual_generation_command_present"]
                and not readiness["manual_generation_executed_by_api"]
                and not readiness["manual_generation_executes_database"]
                and not readiness["manual_generation_executes_telegram"]
                and not boundaries.get("api_generates_report")
                and not boundaries.get("api_writes_report_file")
                and not boundaries.get("api_dispatches_telegram")
                and not boundaries.get("api_writes_database")
                and not boundaries.get("api_attaches_scheduler")
            ),
        },
        {
            "key": "report_run_receipt_provided",
            "label": "操作員需貼回 report run receipt 或 report generation receipt",
            "passed": receipt["provided"],
        },
        {
            "key": "report_run_receipt_mode_and_artifact",
            "label": "receipt 必須是人工/獨立 job 報表產出且有 artifact path/hash",
            "passed": bool(
                receipt["mode"] in EXPECTED_RECEIPT_MODES
                and receipt["report_generated"]
                and receipt["target_report_family"] == readiness["target_report_family"]
                and receipt["language"] == readiness["language"]
                and receipt["report_output_artifact_path"]
                and receipt["report_output_hash"]
            ),
        },
        {
            "key": "report_run_receipt_summary_hash_matches_expected",
            "label": "receipt 的 summary payload hash 必須符合 readiness manifest",
            "passed": receipt["summary_payload_hash_matches_expected"],
        },
        {
            "key": "report_run_receipt_required_sections_present",
            "label": "report receipt 必須列出必要報表章節",
            "passed": receipt["required_report_sections_present"],
        },
        {
            "key": "report_run_receipt_runtime_boundaries",
            "label": "receipt 不得顯示 API 產報表、DB、Telegram、LLM、scheduler 或 review_state 副作用",
            "passed": bool(
                not receipt["generated_by_api"]
                and not receipt["api_writes_file"]
                and not receipt["api_calls_llm"]
                and not receipt["api_dispatches_telegram"]
                and not receipt["api_writes_database"]
                and not receipt["database_write_executed"]
                and not receipt["database_commit_executed"]
                and not receipt["telegram_dispatched"]
                and not receipt["telegram_dispatch_attempted"]
                and not receipt["llm_call_executed"]
                and not receipt["external_network_executed"]
                and not receipt["scheduler_attached"]
                and not receipt["review_state_update_executed"]
            ),
        },
        {
            "key": "report_run_receipt_no_token_key",
            "label": "receipt 不得包含 approval 或 Telegram token key",
            "passed": not receipt["approval_or_telegram_token_key_detected"],
        },
        {
            "key": "operator_confirmed_report_run_receipt",
            "label": "操作員確認 receipt、artifact、hash、章節與 runtime 邊界",
            "passed": bool(
                operator[
                    "telegram_dispatch_report_run_package_artifact_path_recorded"
                ]
                and operator[
                    "telegram_dispatch_report_run_readiness_artifact_path_recorded"
                ]
                and operator["report_output_artifact_path_recorded"]
                and operator["report_run_receipt_artifact_path_recorded"]
                and operator["operator_confirmed_report_run_receipt"]
                and operator["operator_confirmed_report_output_hash_matched"]
                and operator["operator_confirmed_report_sections_reviewed"]
                and operator["operator_confirmed_no_token_in_report_receipt"]
                and operator["operator_confirmed_no_api_report_generation"]
                and operator["operator_confirmed_no_api_telegram_dispatch"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_llm_call"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "report_run_receipt_no_token_submitted_to_api",
            "label": "payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_run_receipt_apply_real_write_not_requested_from_api",
            "label": "API/UI report run receipt 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
        {
            "key": "report_run_readiness_has_no_side_effects",
            "label": "上游 readiness 不得已有 DB、檔案、LLM、Telegram 或 scheduler 副作用",
            "passed": readiness["side_effects_clear"],
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_run_receipt(
    *,
    telegram_dispatch_report_run_readiness,
    report_run_receipt=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report run receipt review；不執行任何副作用。"""
    readiness = _readiness_summary(telegram_dispatch_report_run_readiness)
    receipt_payload = _receipt_payload(operator_evidence, report_run_receipt)
    receipt = _receipt_summary(receipt_payload, readiness)
    operator = _operator_summary(operator_evidence)
    gates = _receipt_gates(
        readiness=readiness,
        receipt=receipt,
        operator=operator,
        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_telegram_dispatch_report_run_receipt_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            SUMMARY_METADATA_KEY,
            "telegram_dispatch_report_run_receipt",
        ],
        "target_operation": "review_manual_market_intel_report_run_receipt",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_run_receipt_reviewed": True,
        "telegram_dispatch_report_run_receipt_passed": receipt_passed,
        "summary_persistence_telegram_dispatch_report_run_receipt_passed": receipt_passed,
        "report_run_receipt_passed": receipt_passed,
        "ready_for_next_manual_phase": receipt_passed,
        "ready_for_market_intel_report_closeout": receipt_passed,
        **{key: False for key in RESPONSE_FALSE_KEYS},
        "statement_count": readiness["statement_count"],
        "expected_summary_payload_hash": readiness["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_run_readiness_summary": readiness,
        "telegram_dispatch_report_run_receipt_summary": receipt,
        "operator_telegram_dispatch_report_run_receipt": operator,
        "promotion_gate": {
            "allowed": receipt_passed,
            "next_manual_phase": "market_intel_report_closeout",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_generate_report": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "保存 report run receipt artifact path",
            "人工確認 report output artifact、hash、section keys 與 readiness manifest 一致",
            "只在 receipt 通過後進入後續 market intel report closeout",
            "不得從 API/UI 補產報表、重跑 LLM、寫 DB、派送 Telegram 或掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_run_receipt_api",
            "do_not_read_telegram_token_from_report_run_receipt_api",
            "do_not_call_llm_from_report_run_receipt",
            "do_not_generate_report_from_report_run_receipt_api",
            "do_not_write_report_artifact_from_report_run_receipt_api",
            "do_not_dispatch_telegram_from_report_run_receipt_api",
            "do_not_open_database_connection_from_report_run_receipt",
            "do_not_update_review_state_from_report_run_receipt",
            "do_not_attach_scheduler_from_report_run_receipt",
            "future_market_intel_report_closeout_must_use_separate_gate",
            "report_run_receipt_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
