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

本模組只把 report input 整理成後續 report run readiness 可審核的 package；
不讀 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"
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 _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 _side_effects_clear(*payloads):
    blocked_keys = (
        "ready_for_report_generation",
        "ready_for_telegram_dispatch",
        "ready_for_manual_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_package_file_written",
        "report_run_package_file_written",
        "telegram_dispatch_report_input_file_written",
        "report_input_file_written",
        "telegram_dispatch_archive_summary_file_written",
        "archive_summary_file_written",
        "telegram_dispatch_archive_file_written",
        "telegram_message_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",
    )
    return all(
        not _as_dict(payload).get(key)
        for payload in payloads
        for key in blocked_keys
    )


def _report_input_summary(telegram_dispatch_report_input):
    report_input = _as_dict(telegram_dispatch_report_input)
    contract = _as_dict(report_input.get("telegram_dispatch_report_input_contract"))
    evidence_refs = _as_dict(contract.get("evidence_refs"))
    artifact_paths = _as_dict(evidence_refs.get("artifact_paths"))
    archive_summary = _as_dict(
        report_input.get("telegram_dispatch_archive_summary_input")
    )
    sections = [
        _as_dict(section)
        for section in _as_list(
            report_input.get("telegram_dispatch_report_input_sections")
        )
    ]
    section_keys = [section.get("key") for section in sections if section.get("key")]
    blocked_reasons = _as_list(report_input.get("blocked_reasons"))
    return {
        "provided": bool(report_input),
        "mode": report_input.get("mode"),
        "target_operation": report_input.get("target_operation"),
        "telegram_dispatch_report_input_ready": bool(
            report_input.get("telegram_dispatch_report_input_ready")
        ),
        "summary_persistence_telegram_dispatch_report_input_ready": bool(
            report_input.get(
                "summary_persistence_telegram_dispatch_report_input_ready"
            )
        ),
        "report_input_ready": bool(report_input.get("report_input_ready")),
        "ready_for_market_intel_report_run_package": bool(
            report_input.get("ready_for_market_intel_report_run_package")
        ),
        "ready_for_next_manual_phase": bool(
            report_input.get("ready_for_next_manual_phase")
        ),
        "ready_for_report_generation": bool(
            report_input.get("ready_for_report_generation")
        ),
        "statement_count": _safe_int(report_input.get("statement_count")),
        "expected_summary_payload_hash": report_input.get(
            "expected_summary_payload_hash"
        ),
        "blocked_count": len(blocked_reasons),
        "report_contract": contract,
        "report_contract_version": contract.get("contract_version"),
        "target_report_family": contract.get("target_report_family"),
        "language": contract.get("language"),
        "required_sections": _as_list(contract.get("required_sections")),
        "report_sections": sections,
        "report_section_keys": section_keys,
        "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,
            ),
            "artifact_paths": artifact_paths,
        },
        "archive_summary": {
            "mode": archive_summary.get("mode"),
            "summary_ready": bool(
                archive_summary.get("telegram_dispatch_archive_summary_ready")
            ),
            "side_effects_clear": bool(archive_summary.get("side_effects_clear")),
        },
        "safe_boundaries": _as_list(report_input.get("safe_boundaries")),
        "side_effects_clear": _side_effects_clear(report_input),
    }


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": _safe_text(
            operator_evidence.get("telegram_dispatch_report_run_package_artifact_path")
            or operator_evidence.get("report_run_package_artifact_path")
            or operator_evidence.get("run_package_artifact_path")
        ),
        "operator_confirmed_telegram_dispatch_report_run_package": bool(
            operator_evidence.get(
                "operator_confirmed_telegram_dispatch_report_run_package"
            )
            or operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_report_run_package"
            )
        ),
        "operator_confirmed_report_run_package_is_read_only": bool(
            operator_evidence.get(
                "operator_confirmed_report_run_package_is_read_only"
            )
            or operator_evidence.get("operator_confirmed_report_package_read_only")
        ),
        "operator_confirmed_report_input_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_input_reviewed")
            or operator_evidence.get(
                "operator_confirmed_telegram_dispatch_report_input_reviewed"
            )
        ),
        "operator_confirmed_report_package_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_package_reviewed")
            or operator_evidence.get("operator_confirmed_run_package_reviewed")
        ),
        "operator_confirmed_report_generation_requires_readiness_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_generation_requires_readiness_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_report_generation_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_run_package": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_run_package"
            )
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "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")
        ),
        "report_run_package_notes_recorded": bool(
            _safe_text(operator_evidence.get("report_run_package_notes"))
            or _safe_text(operator_evidence.get("report_input_notes"))
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _run_package_sections(report_input_summary):
    evidence = report_input_summary["evidence_refs"]
    artifact_paths = evidence["artifact_paths"]
    return [
        {
            "key": "source_report_input",
            "title": "Source report input",
            "facts": [
                f"source_mode={report_input_summary['mode'] or 'missing'}",
                f"statement_count={report_input_summary['statement_count']}",
                f"input_sections={','.join(report_input_summary['report_section_keys']) or 'missing'}",
            ],
        },
        {
            "key": "report_contract",
            "title": "Report contract",
            "facts": [
                f"contract={report_input_summary['report_contract_version'] or 'missing'}",
                f"family={report_input_summary['target_report_family'] or 'missing'}",
                f"language={report_input_summary['language'] or 'missing'}",
            ],
        },
        {
            "key": "evidence_manifest",
            "title": "Evidence manifest",
            "facts": [
                f"message_id={evidence['message_id'] or 'missing'}",
                f"chat_id={evidence['chat_id'] or 'missing'}",
                f"receipt_path={artifact_paths.get('telegram_dispatch_receipt_artifact_path') or 'missing'}",
                f"archive_path={artifact_paths.get('telegram_dispatch_archive_artifact_path') or 'missing'}",
            ],
        },
        {
            "key": "execution_boundaries",
            "title": "Execution boundaries",
            "facts": [
                "report_generation=false",
                "llm_call_executed=false",
                "telegram_dispatched=false",
                "database_write_executed=false",
                "scheduler_attached=false",
            ],
        },
        {
            "key": "future_readiness_gate",
            "title": "Future readiness gate",
            "facts": [
                "next_manual_phase=market_intel_report_run_readiness",
                "report_generation_requires_separate_gate=true",
                "api_must_not_write_artifact=true",
            ],
        },
    ]


def _run_package_contract(report_input_summary, package_sections):
    return {
        "contract_version": "market_intel_telegram_dispatch_report_run_package_v1",
        "language": "zh-TW",
        "source_mode": report_input_summary["mode"],
        "source_contract_version": report_input_summary["report_contract_version"],
        "target_report_family": report_input_summary["target_report_family"],
        "required_package_sections": [
            section["key"] for section in package_sections
        ],
        "source_required_sections": report_input_summary["required_sections"],
        "evidence_refs": report_input_summary["evidence_refs"],
        "intended_report_artifacts": [
            "telegram_dispatch_audit_report_payload",
            "report_generation_readiness_packet",
        ],
        "execution_boundaries": {
            "api_generates_report": False,
            "api_writes_report_file": False,
            "api_calls_llm": False,
            "api_dispatches_telegram": False,
            "api_writes_database": False,
            "api_attaches_scheduler": False,
        },
        "forbidden_actions": [
            "不得從 run package API 產生報表檔",
            "不得從 run package API 呼叫 LLM 或補發 Telegram",
            "不得寫入 DB、review_state 或 artifact manifest",
            "不得把 token、secret 或 shell-only 指令寫入 run package",
        ],
    }


def _report_gates(report_input_summary, operator, package_sections, apply_real_write):
    required_input_sections = {
        "executive_context",
        "telegram_message_evidence",
        "dispatch_audit_evidence",
        "artifact_traceability",
        "runtime_safety",
    }
    required_package_sections = {
        "source_report_input",
        "report_contract",
        "evidence_manifest",
        "execution_boundaries",
        "future_readiness_gate",
    }
    input_section_keys = set(report_input_summary["report_section_keys"])
    package_section_keys = {section["key"] for section in package_sections}
    evidence = report_input_summary["evidence_refs"]
    return [
        {
            "key": "telegram_dispatch_report_input_preview_provided",
            "label": "必須提供 Telegram dispatch report input preview",
            "passed": bool(
                report_input_summary["provided"]
                and report_input_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_input_preview"
            ),
        },
        {
            "key": "telegram_dispatch_report_input_ready",
            "label": "Telegram dispatch report input 必須已通過且尚未產報表",
            "passed": bool(
                report_input_summary["telegram_dispatch_report_input_ready"]
                and report_input_summary[
                    "summary_persistence_telegram_dispatch_report_input_ready"
                ]
                and report_input_summary["report_input_ready"]
                and report_input_summary["ready_for_market_intel_report_run_package"]
                and report_input_summary["ready_for_next_manual_phase"]
                and not report_input_summary["ready_for_report_generation"]
            ),
        },
        {
            "key": "telegram_dispatch_report_input_contract_complete",
            "label": "report input contract 必須完整保留 family、language、evidence refs",
            "passed": bool(
                report_input_summary["report_contract_version"]
                == "market_intel_telegram_dispatch_report_input_v1"
                and report_input_summary["target_report_family"]
                and report_input_summary["language"] == "zh-TW"
                and evidence["message_id"]
                and evidence["chat_id"]
                and evidence["telegram_channel_label"]
                and evidence["summary_payload_hash"]
            ),
        },
        {
            "key": "telegram_dispatch_report_input_sections_complete",
            "label": "report input sections 與 run package sections 必須完整",
            "passed": bool(
                required_input_sections.issubset(input_section_keys)
                and required_package_sections.issubset(package_section_keys)
            ),
        },
        {
            "key": "telegram_dispatch_report_input_side_effects_clear",
            "label": "report input payload 不得顯示報表、Telegram、DB、LLM、檔案或 scheduler 副作用",
            "passed": report_input_summary["side_effects_clear"],
        },
        {
            "key": "operator_confirmed_telegram_dispatch_report_run_package",
            "label": "操作員確認本階段只整理 report run package",
            "passed": bool(
                operator["operator_confirmed_telegram_dispatch_report_run_package"]
                and operator[
                    "operator_confirmed_report_run_package_is_read_only"
                ]
                and operator["operator_confirmed_report_input_reviewed"]
                and operator["operator_confirmed_report_package_reviewed"]
                and operator[
                    "operator_confirmed_report_generation_requires_readiness_gate"
                ]
            ),
        },
        {
            "key": "operator_confirmed_report_run_package_runtime_boundaries",
            "label": "操作員確認 run package 不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_run_package"]
                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": "telegram_dispatch_report_run_package_artifact_path_recorded",
            "label": "report run package artifact path 必須由操作員提供",
            "passed": bool(
                operator["telegram_dispatch_report_run_package_artifact_path"]
            ),
        },
        {
            "key": "telegram_dispatch_report_run_package_no_token_submitted_to_api",
            "label": "run package payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_report_run_package_apply_real_write_not_requested_from_api",
            "label": "API/UI report run package 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_run_package(
    *,
    telegram_dispatch_report_input,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report run package gate；不執行任何副作用。"""
    report_input_summary = _report_input_summary(telegram_dispatch_report_input)
    operator = _operator_summary(operator_evidence)
    package_sections = _run_package_sections(report_input_summary)
    run_package = _run_package_contract(report_input_summary, package_sections)
    gates = _report_gates(
        report_input_summary,
        operator,
        package_sections,
        bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    package_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_run_package_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            SUMMARY_METADATA_KEY,
            "telegram_dispatch_report_run_package",
        ],
        "target_operation": "prepare_manual_market_intel_report_run_package",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_run_package_reviewed": True,
        "telegram_dispatch_report_run_package_ready": package_ready,
        "summary_persistence_telegram_dispatch_report_run_package_ready": package_ready,
        "report_run_package_ready": package_ready,
        "ready_for_next_manual_phase": package_ready,
        "ready_for_market_intel_report_run_readiness": package_ready,
        "ready_for_report_generation": False,
        "ready_for_ai_summary_generation": False,
        "ready_for_llm_call": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_manual_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_real_write": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_dispatches_telegram": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "telegram_dispatch_report_run_package_file_written": False,
        "report_run_package_file_written": False,
        "telegram_dispatch_report_input_file_written": False,
        "report_input_file_written": False,
        "telegram_dispatch_archive_summary_file_written": False,
        "archive_summary_file_written": False,
        "telegram_dispatch_archive_file_written": False,
        "telegram_message_file_written": False,
        "report_file_written": False,
        "report_record_written": False,
        "report_manifest_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_manifest_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": False,
        "telegram_dispatch_attempted": 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": report_input_summary["statement_count"],
        "expected_summary_payload_hash": report_input_summary[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_input_summary": report_input_summary,
        "telegram_dispatch_report_run_package_sections": package_sections,
        "telegram_dispatch_report_run_package": run_package,
        "operator_telegram_dispatch_report_run_package": operator,
        "promotion_gate": {
            "allowed": package_ready,
            "next_manual_phase": "market_intel_report_run_readiness",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "future_report_generation_requires_separate_gate": True,
            "api_must_not_dispatch_telegram": True,
            "api_must_not_generate_report": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch report run package artifact path",
            "確認 run package 只引用 report input contract 與 evidence refs",
            "後續若要產製報表，必須另開 report run readiness gate",
            "不得從 run package API 呼叫 LLM、派送 Telegram、寫 DB、寫 artifact 或掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_report_run_package_api",
            "do_not_read_telegram_token_from_telegram_dispatch_report_run_package_api",
            "do_not_call_llm_from_telegram_dispatch_report_run_package",
            "do_not_dispatch_telegram_from_telegram_dispatch_report_run_package_api",
            "do_not_open_database_connection_from_telegram_dispatch_report_run_package",
            "do_not_write_report_run_package_artifact_from_api",
            "do_not_generate_report_from_telegram_dispatch_report_run_package_api",
            "do_not_update_review_state_from_telegram_dispatch_report_run_package",
            "do_not_attach_scheduler_from_telegram_dispatch_report_run_package",
            "future_report_generation_must_use_separate_readiness_gate",
            "telegram_dispatch_report_run_package_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
