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

本模組只在 report archive 通過後整理長期查閱與後續 catalog handoff 所需
summary input；不讀 approval 或 Telegram token、不呼叫 LLM、不補產報表、
不派送 Telegram、不開 DB、不寫檔、不更新 review_state、不掛 scheduler。
"""

from services.market_intel.candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive import (
    FALSE_RESPONSE_KEYS as REPORT_ARCHIVE_FALSE_RESPONSE_KEYS,
    REQUIRED_CLOSEOUT_BOUNDARIES,
    SAFE_APPROVAL_ENV_VAR,
    SAFE_TOKEN_METADATA_KEYS,
    SUMMARY_METADATA_KEY,
    TARGET_COLUMN,
    TARGET_TABLE,
    _as_dict,
    _as_list,
    _contains_forbidden_token_key,
    _has_text,
    _safe_int,
    _safe_text,
    _strip_safe_token_boolean_keys,
)


REQUIRED_ARCHIVE_BOUNDARIES = {
    "do_not_read_approval_token_from_report_archive_api",
    "do_not_read_telegram_token_from_report_archive_api",
    "do_not_call_llm_from_report_archive",
    "do_not_generate_report_from_report_archive_api",
    "do_not_write_archive_artifact_from_report_archive_api",
    "do_not_dispatch_telegram_from_report_archive_api",
    "do_not_open_database_connection_from_report_archive",
    "do_not_update_review_state_from_report_archive",
    "do_not_attach_scheduler_from_report_archive",
    "future_market_intel_report_archive_summary_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_ARCHIVE_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_archive_summary_file_written",
            "report_archive_summary_file_written",
            "archive_summary_file_written",
            "report_summary_input_file_written",
        )
    )
)


def _report_archive_summary(telegram_dispatch_report_archive):
    archive = _as_dict(telegram_dispatch_report_archive)
    closeout = _as_dict(archive.get("telegram_dispatch_report_closeout_summary"))
    operator_archive = _as_dict(archive.get("operator_telegram_dispatch_report_archive"))
    promotion = _as_dict(archive.get("promotion_gate"))
    safe_boundaries = set(str(item) for item in _as_list(archive.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_ARCHIVE_BOUNDARIES - safe_boundaries)
    closeout_safe_boundaries = set(_as_list(closeout.get("safe_boundaries")))
    missing_closeout_boundaries = sorted(
        REQUIRED_CLOSEOUT_BOUNDARIES - closeout_safe_boundaries
    )

    return {
        "provided": bool(archive),
        "mode": archive.get("mode"),
        "target_operation": archive.get("target_operation"),
        "archive_passed": bool(
            archive.get("telegram_dispatch_report_archive_passed")
            or archive.get("summary_persistence_telegram_dispatch_report_archive_passed")
            or archive.get("report_archive_passed")
        ),
        "ready_for_market_intel_report_archive_summary": bool(
            archive.get("ready_for_market_intel_report_archive_summary")
        ),
        "ready_for_next_manual_phase": bool(archive.get("ready_for_next_manual_phase")),
        "statement_count": _safe_int(archive.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            archive.get("expected_summary_payload_hash")
            or closeout.get("expected_summary_payload_hash"),
            80,
        ),
        "target_report_family": closeout.get("target_report_family"),
        "language": closeout.get("language"),
        "report_output_artifact_path": closeout.get("report_output_artifact_path"),
        "report_output_hash": closeout.get("report_output_hash"),
        "summary_payload_hash": closeout.get("summary_payload_hash"),
        "summary_payload_hash_matches_expected": bool(
            closeout.get("summary_payload_hash_matches_expected")
        ),
        "required_report_sections_present": bool(
            closeout.get("required_report_sections_present")
        ),
        "section_keys": _as_list(closeout.get("section_keys")),
        "report_archive_artifact_path_recorded": bool(
            operator_archive.get("report_archive_artifact_path_recorded")
        ),
        "report_closeout_artifact_path_recorded": bool(
            operator_archive.get("report_closeout_artifact_path_recorded")
        ),
        "report_run_receipt_artifact_path_recorded": bool(
            operator_archive.get("report_run_receipt_artifact_path_recorded")
        ),
        "report_output_artifact_path_recorded": bool(
            operator_archive.get("report_output_artifact_path_recorded")
        ),
        "operator_confirmed_report_archive": bool(
            operator_archive.get("operator_confirmed_report_archive")
        ),
        "operator_confirmed_report_closeout_archived": bool(
            operator_archive.get("operator_confirmed_report_closeout_archived")
        ),
        "operator_confirmed_report_receipt_archived": bool(
            operator_archive.get("operator_confirmed_report_receipt_archived")
        ),
        "operator_confirmed_report_output_archived": bool(
            operator_archive.get("operator_confirmed_report_output_archived")
        ),
        "operator_confirmed_report_output_hash_matched": bool(
            operator_archive.get("operator_confirmed_report_output_hash_matched")
        ),
        "operator_confirmed_report_sections_reviewed": bool(
            operator_archive.get("operator_confirmed_report_sections_reviewed")
        ),
        "operator_confirmed_archive_manifest_reviewed": bool(
            operator_archive.get("operator_confirmed_archive_manifest_reviewed")
        ),
        "operator_confirmed_archive_retention_policy_recorded": bool(
            operator_archive.get("operator_confirmed_archive_retention_policy_recorded")
        ),
        "operator_confirmed_report_archive_summary_requires_separate_gate": bool(
            operator_archive.get(
                "operator_confirmed_report_archive_summary_requires_separate_gate"
            )
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_summary_separate_gate": bool(
            promotion.get("report_archive_summary_requires_separate_gate")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "closeout_safe_boundaries_complete": not missing_closeout_boundaries,
        "missing_closeout_safe_boundaries": missing_closeout_boundaries,
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(archive)
        ),
        "blocked_count": len(_as_list(archive.get("blocked_reasons"))),
        **{key: bool(archive.get(key)) for key in FALSE_RESPONSE_KEYS},
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "report_archive_summary_artifact_path": _safe_text(
            operator_evidence.get("report_archive_summary_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_archive_summary_artifact_path"
            )
            or operator_evidence.get("market_intel_report_archive_summary_artifact_path")
        ),
        "report_archive_artifact_path_recorded": _has_text(
            operator_evidence.get("report_archive_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_archive_artifact_path")
        ),
        "report_closeout_artifact_path_recorded": _has_text(
            operator_evidence.get("report_closeout_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_closeout_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"
            )
        ),
        "report_output_artifact_path_recorded": _has_text(
            operator_evidence.get("report_output_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_output_artifact_path")
        ),
        "operator_confirmed_report_archive_summary": bool(
            operator_evidence.get("operator_confirmed_report_archive_summary")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_archive_summary"
            )
        ),
        "operator_confirmed_summary_is_read_only": bool(
            operator_evidence.get("operator_confirmed_report_archive_summary_read_only")
            or operator_evidence.get("operator_confirmed_summary_is_read_only")
        ),
        "operator_confirmed_report_archive_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_archive_reviewed")
            or operator_evidence.get("operator_confirmed_report_archive")
        ),
        "operator_confirmed_report_traceability_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_traceability_reviewed")
            or operator_evidence.get("operator_confirmed_report_output_hash_matched")
        ),
        "operator_confirmed_report_catalog_handoff_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_handoff_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_archive_summary": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_archive_summary"
            )
            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_file_write": bool(
            operator_evidence.get("operator_confirmed_no_api_file_write")
            or operator_evidence.get("operator_confirmed_no_archive_summary_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")
        ),
        "archive_summary_notes_recorded": _has_text(
            operator_evidence.get("report_archive_summary_notes")
            or operator_evidence.get("archive_summary_notes")
        ),
        "safe_token_metadata_only": all(
            key in SAFE_TOKEN_METADATA_KEYS or key == "approval_env_var"
            for key in operator_evidence
            if "token" in str(key).lower() or str(key).lower() == "approval_env_var"
        )
        and operator_evidence.get("approval_env_var", SAFE_APPROVAL_ENV_VAR)
        == SAFE_APPROVAL_ENV_VAR,
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _summary_sections(archive_summary):
    artifact_count = sum(
        1
        for key in (
            "report_archive_artifact_path_recorded",
            "report_closeout_artifact_path_recorded",
            "report_run_receipt_artifact_path_recorded",
            "report_output_artifact_path_recorded",
        )
        if archive_summary[key]
    )
    return [
        {
            "key": "report_identity",
            "title": "Report identity",
            "facts": [
                f"family={archive_summary['target_report_family'] or 'missing'}",
                f"language={archive_summary['language'] or 'missing'}",
                f"report_path={archive_summary['report_output_artifact_path'] or 'missing'}",
                f"report_hash={archive_summary['report_output_hash'] or 'missing'}",
            ],
        },
        {
            "key": "archive_traceability",
            "title": "Archive traceability",
            "facts": [
                f"artifact_path_count={artifact_count}",
                f"statement_count={archive_summary['statement_count']}",
                f"archive_passed={archive_summary['archive_passed']}",
            ],
        },
        {
            "key": "integrity_review",
            "title": "Integrity review",
            "facts": [
                f"summary_hash_matched={archive_summary['summary_payload_hash_matches_expected']}",
                f"sections_present={archive_summary['required_report_sections_present']}",
                f"section_count={len(archive_summary['section_keys'])}",
                f"retention_recorded={archive_summary['operator_confirmed_archive_retention_policy_recorded']}",
            ],
        },
        {
            "key": "runtime_safety",
            "title": "Runtime safety",
            "facts": [
                "report_generated=false",
                "file_written=false",
                "telegram_dispatched=false",
                "database_write_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _summary_gates(archive_summary, operator, apply_real_write):
    return [
        {
            "key": "report_archive_preview_provided",
            "label": "必須提供上一階段 report archive preview",
            "passed": bool(
                archive_summary["provided"]
                and archive_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_preview"
            ),
        },
        {
            "key": "report_archive_passed",
            "label": "report archive 必須已通過",
            "passed": archive_summary["archive_passed"],
        },
        {
            "key": "report_archive_ready_for_summary",
            "label": "report archive 必須只放行到 report archive summary",
            "passed": bool(
                archive_summary["ready_for_market_intel_report_archive_summary"]
                and archive_summary["ready_for_next_manual_phase"]
                and archive_summary["promotion_allowed"]
                and archive_summary["promotion_next_manual_phase"]
                == "market_intel_report_archive_summary"
                and archive_summary["promotion_summary_separate_gate"]
            ),
        },
        {
            "key": "report_archive_traceability_complete",
            "label": "archive summary 必須保留 report output、receipt、closeout 與 archive trace",
            "passed": bool(
                archive_summary["report_output_artifact_path"]
                and archive_summary["report_output_hash"]
                and archive_summary["summary_payload_hash_matches_expected"]
                and archive_summary["required_report_sections_present"]
                and archive_summary["report_archive_artifact_path_recorded"]
                and archive_summary["report_closeout_artifact_path_recorded"]
                and archive_summary["report_run_receipt_artifact_path_recorded"]
                and archive_summary["report_output_artifact_path_recorded"]
                and archive_summary["operator_confirmed_report_archive"]
                and archive_summary["operator_confirmed_report_closeout_archived"]
                and archive_summary["operator_confirmed_report_receipt_archived"]
                and archive_summary["operator_confirmed_report_output_archived"]
                and archive_summary["operator_confirmed_report_output_hash_matched"]
                and archive_summary["operator_confirmed_report_sections_reviewed"]
                and archive_summary["operator_confirmed_archive_manifest_reviewed"]
                and archive_summary[
                    "operator_confirmed_archive_retention_policy_recorded"
                ]
            ),
        },
        {
            "key": "report_archive_runtime_boundaries_clear",
            "label": "archive payload 不得顯示 API 產報表、寫檔、DB、Telegram、LLM 或 scheduler 副作用",
            "passed": all(not archive_summary[key] for key in FALSE_RESPONSE_KEYS),
        },
        {
            "key": "report_archive_safe_boundaries_complete",
            "label": "archive 必須保留 archive summary separate gate 與 runtime 安全邊界",
            "passed": archive_summary["safe_boundaries_complete"],
        },
        {
            "key": "report_archive_no_token_key",
            "label": "archive payload 不得包含 approval 或 Telegram token key",
            "passed": not archive_summary["forbidden_token_key_detected"],
        },
        {
            "key": "report_archive_summary_artifacts_recorded",
            "label": "操作員需記錄 archive summary、archive、closeout、receipt 與 report output artifact path",
            "passed": bool(
                operator["report_archive_summary_artifact_path"]
                and operator["report_archive_artifact_path_recorded"]
                and operator["report_closeout_artifact_path_recorded"]
                and operator["report_run_receipt_artifact_path_recorded"]
                and operator["report_output_artifact_path_recorded"]
            ),
        },
        {
            "key": "operator_confirmed_report_archive_summary",
            "label": "操作員確認 summary 只整理已封存報表事實，且下一階段另開 gate",
            "passed": bool(
                operator["operator_confirmed_report_archive_summary"]
                and operator["operator_confirmed_summary_is_read_only"]
                and operator["operator_confirmed_report_archive_reviewed"]
                and operator["operator_confirmed_report_traceability_reviewed"]
                and operator[
                    "operator_confirmed_report_catalog_handoff_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "operator_confirmed_report_archive_summary_runtime_boundaries",
            "label": "操作員確認本 API 不產報表、不寫檔、不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_archive_summary"]
                and operator["operator_confirmed_no_api_report_generation"]
                and operator["operator_confirmed_no_api_file_write"]
                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_archive_summary_no_token_submitted_to_api",
            "label": "archive summary payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_archive_summary_apply_real_write_not_requested_from_api",
            "label": "API/UI report archive summary 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_summary(
    *,
    telegram_dispatch_report_archive,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report archive summary gate；不執行任何副作用。"""
    archive_summary = _report_archive_summary(telegram_dispatch_report_archive)
    operator = _operator_summary(operator_evidence)
    sections = _summary_sections(archive_summary)
    gates = _summary_gates(archive_summary, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    summary_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_summary_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            SUMMARY_METADATA_KEY,
            "telegram_dispatch_report_archive_summary",
        ],
        "target_operation": "summarize_archived_market_intel_report",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_archive_summary_reviewed": True,
        "telegram_dispatch_report_archive_summary_passed": summary_passed,
        "summary_persistence_telegram_dispatch_report_archive_summary_passed": summary_passed,
        "report_archive_summary_passed": summary_passed,
        "ready_for_next_manual_phase": summary_passed,
        "ready_for_market_intel_report_catalog_handoff": summary_passed,
        **{key: False for key in FALSE_RESPONSE_KEYS},
        "statement_count": archive_summary["statement_count"],
        "expected_summary_payload_hash": archive_summary[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_archive_summary": archive_summary,
        "telegram_dispatch_report_archive_summary_sections": sections,
        "operator_telegram_dispatch_report_archive_summary": operator,
        "promotion_gate": {
            "allowed": summary_passed,
            "next_manual_phase": "market_intel_report_catalog_handoff",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_generate_report": True,
            "api_must_not_write_summary_file": True,
            "api_must_not_dispatch_telegram": True,
            "report_catalog_handoff_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report archive summary artifact path",
            "確認 summary sections 只包含 report identity、archive trace、integrity 與 runtime safety",
            "下一階段 report catalog handoff 必須另開 gate；本 API 不寫檔、不補產報表",
            "若任何 archive summary gate 阻擋，停在 report archive 階段並保留 feature flags 關閉",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_archive_summary_api",
            "do_not_read_telegram_token_from_report_archive_summary_api",
            "do_not_call_llm_from_report_archive_summary",
            "do_not_generate_report_from_report_archive_summary_api",
            "do_not_write_report_archive_summary_artifact_from_api",
            "do_not_dispatch_telegram_from_report_archive_summary_api",
            "do_not_open_database_connection_from_report_archive_summary",
            "do_not_update_review_state_from_report_archive_summary",
            "do_not_attach_scheduler_from_report_archive_summary",
            "future_market_intel_report_catalog_handoff_must_use_separate_gate",
            "report_archive_summary_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
