"""
IwoooS 安全治理 API。

Wazuh 接線採用只讀 metadata 模式：預設關閉、不保存 raw payload、
不公開 agent 原名 / 內網 IP、不啟用 active response。
"""

from __future__ import annotations

import asyncio
import json
from typing import Any

from fastapi import APIRouter, HTTPException, status
from fastapi.responses import JSONResponse

from src.services.iwooos_high_value_config_control_coverage import (
    load_latest_iwooos_high_value_config_control_coverage,
)
from src.services.iwooos_owner_evidence_intake_preflight import (
    load_latest_iwooos_owner_evidence_intake_preflight,
)
from src.services.iwooos_runtime_security_readback import (
    load_latest_iwooos_runtime_security_readback,
)
from src.services.iwooos_security_operating_system import (
    load_latest_iwooos_security_operating_system,
)
from src.services.iwooos_security_operating_system import (
    validate_iwooos_security_operation_packet as validate_iwooos_security_operation_packet_payload,
)
from src.services.iwooos_security_control_coverage import (
    load_latest_iwooos_security_control_coverage,
)
from src.services.iwooos_wazuh_allowlisted_check_mode_dry_run import (
    load_latest_iwooos_wazuh_allowlisted_check_mode_dry_run,
)
from src.services.iwooos_wazuh_allowlisted_check_mode_dry_run import (
    validate_iwooos_wazuh_allowlisted_check_mode_dry_run_packet as validate_wazuh_allowlisted_check_mode_dry_run_packet_payload,
)
from src.services.iwooos_wazuh_live_metadata_gate import (
    load_latest_iwooos_wazuh_live_metadata_gate,
)
from src.services.iwooos_wazuh_live_metadata_gate import (
    validate_iwooos_wazuh_live_metadata_owner_packet as validate_wazuh_live_metadata_owner_packet_payload,
)
from src.services.iwooos_wazuh_managed_host_coverage import (
    load_latest_iwooos_wazuh_managed_host_coverage,
)
from src.services.iwooos_wazuh_manager_registry_reviewer_validation import (
    load_latest_iwooos_wazuh_manager_registry_reviewer_validation,
)
from src.services.iwooos_wazuh_manager_registry_reviewer_validation import (
    validate_iwooos_wazuh_manager_registry_acceptance_evidence as validate_wazuh_manager_registry_acceptance_evidence_payload,
)
from src.services.iwooos_wazuh_manager_registry_reviewer_validation import (
    validate_iwooos_wazuh_manager_registry_owner_export as validate_wazuh_manager_registry_owner_export_payload,
)
from src.services.iwooos_wazuh_owner_evidence_preflight import (
    load_latest_iwooos_wazuh_owner_evidence_preflight,
)
from src.services.iwooos_wazuh_readonly_status import (
    load_iwooos_wazuh_readonly_status,
)
from src.services.iwooos_wazuh_runtime_controlled_apply_preflight import (
    load_latest_iwooos_wazuh_runtime_controlled_apply_preflight,
)
from src.services.iwooos_wazuh_runtime_controlled_apply_preflight import (
    validate_iwooos_wazuh_runtime_controlled_apply_packet as validate_wazuh_runtime_controlled_apply_packet_payload,
)
from src.services.iwooos_wazuh_runtime_gate_owner_review_readback import (
    load_latest_iwooos_wazuh_runtime_gate_owner_review_readback,
)
from src.services.iwooos_wazuh_runtime_gate_owner_review_readback import (
    validate_iwooos_wazuh_runtime_gate_owner_review_packet as validate_wazuh_runtime_gate_owner_review_packet_payload,
)
from src.services.public_redaction import redact_public_lan_topology

router = APIRouter(tags=["IwoooS Security"])


async def _wazuh_readonly_status() -> JSONResponse:
    result = await load_iwooos_wazuh_readonly_status()
    return JSONResponse(status_code=result.http_status, content=result.payload)


@router.get("/api/iwooos/wazuh")
async def get_iwooos_wazuh_readonly_status_compat() -> JSONResponse:
    return await _wazuh_readonly_status()


@router.get("/api/v1/iwooos/wazuh")
async def get_iwooos_wazuh_readonly_status_v1() -> JSONResponse:
    return await _wazuh_readonly_status()


@router.get(
    "/api/v1/iwooos/security-operating-system",
    response_model=dict[str, Any],
    summary="取得 IwoooS 資安作業系統總入口",
    description=(
        "讀取已提交的 IwoooS security operating system contract，回傳資安框架、角色、"
        "severity lane、P0/P1/P2 workstream、告警訊息合約、自動化 loop、驗證節點、"
        "no-false-green 規則與 operation packet validator。此端點不查 live host、不讀 secret、"
        "不送告警、不啟動 active response、不改 Nginx / Docker / K8s / firewall。"
    ),
)
async def get_iwooos_security_operating_system() -> dict[str, Any]:
    """回傳 IwoooS 資安作業系統公開安全總入口。"""
    try:
        payload = await asyncio.to_thread(load_latest_iwooos_security_operating_system)
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS security operating system 無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/security-operating-system/validate-operation-packet",
    response_model=dict[str, Any],
    summary="驗證 IwoooS 資安作業脫敏 operation packet",
    description=(
        "針對單次 redacted security operation packet 進行 no-persist review validation，"
        "檢查告警訊息合約、severity lane、target selector、source-of-truth diff、check-mode / dry-run、"
        "rollback、post-apply verifier、KM / PlayBook writeback 與邊界 ack。此端點不保存 payload、"
        "不查 live host / Wazuh / Kali、不讀或回傳機密明文、不送 Telegram、不啟用 SOAR / active response、"
        "不改 Nginx / Docker / K8s / firewall，也不更新 runtime gate 總帳。"
    ),
)
async def validate_iwooos_security_operation_packet(
    operation_packet: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 IwoooS security operation packet 的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_iwooos_security_operation_packet_payload,
            operation_packet,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS security operation packet 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-live-metadata-gate",
    response_model=dict[str, Any],
    summary="取得 Wazuh 即時中繼資料負責人閘門讀回",
    description=(
        "讀取已提交的 Wazuh 即時中繼資料負責人閘門，並附上 Wazuh 正式只讀路由的"
        "公開安全彙總。此端點不讀機密明文、不查主機、不保存原始 Wazuh 載荷、"
        "不啟用主動回應、不改 K8s / ArgoCD / Docker / Nginx / firewall。"
    ),
)
async def get_iwooos_wazuh_live_metadata_gate() -> dict[str, Any]:
    """回傳 Wazuh 即時中繼資料啟用前負責人閘門只讀狀態。"""
    try:
        wazuh_result = await load_iwooos_wazuh_readonly_status()
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_live_metadata_gate,
            wazuh_live_status=wazuh_result.payload,
            wazuh_live_http_status=wazuh_result.http_status,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh 即時中繼資料閘門無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-live-metadata-gate/validate-live-metadata-owner-packet",
    response_model=dict[str, Any],
    summary="驗證 Wazuh 即時中繼資料脫敏 owner packet",
    description=(
        "針對單次 owner / reviewer 提供的 redacted Wazuh live metadata owner packet "
        "進行 no-persist metadata review validation，回傳 accepted-for-review / needs supplement / "
        "quarantined / rejected runtime action 分流。此端點不保存 payload、不查 live Wazuh API、"
        "不讀主機、不讀或回傳機密明文、不保存原始 Wazuh 載荷、不啟用主動回應、不改 K8s / "
        "ArgoCD / Docker / Nginx / firewall，也不更新 live metadata gate 總帳。"
    ),
)
async def validate_iwooos_wazuh_live_metadata_owner_packet(
    live_metadata_owner_packet: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh live metadata owner packet 的公開安全驗證結果。"""
    try:
        wazuh_result = await load_iwooos_wazuh_readonly_status()
        payload = await asyncio.to_thread(
            validate_wazuh_live_metadata_owner_packet_payload,
            live_metadata_owner_packet,
            wazuh_live_status=wazuh_result.payload,
            wazuh_live_http_status=wazuh_result.http_status,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh 即時中繼資料 owner packet 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-owner-evidence-preflight",
    response_model=dict[str, Any],
    summary="取得 Wazuh 負責人證據收件預檢讀回",
    description=(
        "讀取已提交的 Wazuh 代理清單負責人證據收件預檢，回傳公開安全的欄位數、"
        "審查檢查、分流、拒收內容計數與 0 / false 邊界。此端點不查 Wazuh、"
        "不讀主機、不保存原始載荷、不收機密明文、不啟用主動回應、不改 Nginx / "
        "Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_owner_evidence_preflight() -> dict[str, Any]:
    """回傳 Wazuh manager registry 負責人證據收件預檢只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_owner_evidence_preflight
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh 負責人證據預檢無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-managed-host-coverage",
    response_model=dict[str, Any],
    summary="取得 Wazuh 受管主機覆蓋只讀讀回",
    description=(
        "讀取已提交的 Wazuh 受管主機覆蓋快照，回傳公開別名主機矩陣、manager registry "
        "接受數、缺口數、必要驗收證據與 0 / false 邊界。此端點不查 Wazuh API、"
        "不讀主機、不重新註冊 agent、不重啟 Wazuh、不保存原始載荷、不收機密明文、"
        "不啟用主動回應、不改 Nginx / Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_managed_host_coverage() -> dict[str, Any]:
    """回傳 Wazuh 受管主機覆蓋公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_managed_host_coverage
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh 受管主機覆蓋無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-manager-registry-reviewer-validation",
    response_model=dict[str, Any],
    summary="取得 Wazuh manager registry reviewer validation 只讀讀回",
    description=(
        "讀取已提交的 Wazuh manager registry reviewer validation contract，回傳 owner export "
        "必要欄位、reviewer 檢查、evidence slots、結果分流、拒收內容與 0 / false 邊界。"
        "此端點不收 raw payload、不查 Wazuh API、不讀主機、不重新註冊 agent、不重啟服務、"
        "不保存機密、不啟用主動回應、不改 Nginx / Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_manager_registry_reviewer_validation() -> dict[str, Any]:
    """回傳 Wazuh manager registry reviewer validation 公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_manager_registry_reviewer_validation
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh manager registry reviewer validation 無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-manager-registry-reviewer-validation/validate-owner-export",
    response_model=dict[str, Any],
    summary="驗證 Wazuh manager registry 脫敏 owner export",
    description=(
        "針對單次 owner-provided redacted Wazuh manager registry export 進行 no-persist reviewer "
        "validation，回傳 accepted / needs supplement / quarantined / rejected runtime action 分流。"
        "此端點不保存 payload、不查 Wazuh API、不讀主機、不重新註冊 agent、不重啟服務、不讀或回傳"
        "機密明文、不啟用主動回應、不改 Nginx / Docker / K8s / firewall，也不更新 manager registry "
        "accepted 總帳。"
    ),
)
async def validate_iwooos_wazuh_manager_registry_owner_export(
    owner_export: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh manager registry 脫敏匯出的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_wazuh_manager_registry_owner_export_payload,
            owner_export,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh manager registry owner export 驗證器無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-manager-registry-reviewer-validation/validate-manager-registry-acceptance",
    response_model=dict[str, Any],
    summary="驗證 Wazuh manager registry accepted 脫敏 evidence packet",
    description=(
        "針對單次 owner / reviewer 提供的 redacted Wazuh manager registry acceptance evidence "
        "packet 進行 no-persist review readiness validation，回傳 accepted-for-review / needs supplement / "
        "quarantined / rejected runtime action 分流。此端點不保存 payload、不查 Wazuh API、不讀主機、"
        "不重新註冊 agent、不重啟服務、不讀或回傳機密明文、不啟用主動回應、不改 Nginx / Docker / "
        "K8s / firewall，也不更新 manager registry accepted 總帳。"
    ),
)
async def validate_iwooos_wazuh_manager_registry_acceptance_evidence(
    acceptance_evidence: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh manager registry accepted evidence 的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_wazuh_manager_registry_acceptance_evidence_payload,
            acceptance_evidence,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh manager registry acceptance evidence 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-runtime-controlled-apply-preflight",
    response_model=dict[str, Any],
    summary="取得 Wazuh runtime controlled apply preflight 只讀讀回",
    description=(
        "讀取已提交的 Wazuh runtime controlled apply preflight contract，回傳 target selector、"
        "source-of-truth diff、check-mode / dry-run、rollback、post-apply verifier、KM / PlayBook "
        "writeback 與 0 / false 邊界。此端點不查 Wazuh API、不讀主機、不重新註冊 agent、"
        "不重啟服務、不保存機密、不啟用主動回應、不改 Nginx / Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_runtime_controlled_apply_preflight() -> dict[str, Any]:
    """回傳 Wazuh runtime controlled apply preflight 公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_runtime_controlled_apply_preflight
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh runtime controlled apply preflight 無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-runtime-controlled-apply-preflight/validate-controlled-apply-packet",
    response_model=dict[str, Any],
    summary="驗證 Wazuh runtime controlled apply 脫敏 preflight packet",
    description=(
        "針對單次 owner / reviewer 提供的 redacted Wazuh runtime controlled apply preflight packet "
        "進行 no-persist review readiness validation，回傳 accepted-for-review / needs supplement / "
        "quarantined / rejected runtime action 分流。此端點不保存 payload、不查 Wazuh API、不讀主機、"
        "不重新註冊 agent、不重啟服務、不讀或回傳機密明文、不啟用主動回應、不改 Nginx / Docker / "
        "K8s / firewall，也不更新 runtime gate 總帳。"
    ),
)
async def validate_iwooos_wazuh_runtime_controlled_apply_packet(
    controlled_apply_packet: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh runtime controlled apply preflight packet 的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_wazuh_runtime_controlled_apply_packet_payload,
            controlled_apply_packet,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh runtime controlled apply preflight packet 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-allowlisted-check-mode-dry-run",
    response_model=dict[str, Any],
    summary="取得 Wazuh allowlisted check-mode dry-run 只讀讀回",
    description=(
        "讀取已提交的 Wazuh allowlisted check-mode dry-run contract，回傳公開別名 selector、"
        "check-mode plan、dry-run evidence refs、redaction attestation、post dry-run verifier、"
        "rollback revalidation、KM / PlayBook writeback 與 0 / false 邊界。此端點不查 Wazuh API、"
        "不讀主機、不保存 raw output、不讀或回傳機密明文、不啟用主動回應、不改 Nginx / "
        "Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_allowlisted_check_mode_dry_run() -> dict[str, Any]:
    """回傳 Wazuh allowlisted check-mode dry-run 公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_allowlisted_check_mode_dry_run
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh allowlisted check-mode dry-run 無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-allowlisted-check-mode-dry-run/validate-dry-run-packet",
    response_model=dict[str, Any],
    summary="驗證 Wazuh allowlisted check-mode dry-run 脫敏 packet",
    description=(
        "針對單次 owner / reviewer 提供的 redacted Wazuh allowlisted check-mode dry-run packet "
        "進行 no-persist readiness validation，回傳 accepted-for-readback / needs supplement / "
        "quarantined / rejected runtime action 分流。此端點不保存 payload、不查 Wazuh API、不讀主機、"
        "不保存 raw output、不讀或回傳機密明文、不啟用主動回應、不改 Nginx / Docker / "
        "K8s / firewall，也不更新 runtime gate 總帳。"
    ),
)
async def validate_iwooos_wazuh_allowlisted_check_mode_dry_run_packet(
    dry_run_packet: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh allowlisted check-mode dry-run packet 的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_wazuh_allowlisted_check_mode_dry_run_packet_payload,
            dry_run_packet,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh allowlisted check-mode dry-run packet 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/wazuh-runtime-gate-owner-review-readback",
    response_model=dict[str, Any],
    summary="取得 Wazuh runtime gate owner-review 只讀讀回",
    description=(
        "讀取已提交的 Wazuh runtime gate owner-review readback contract，回傳 owner-review "
        "decision、target selector、source-of-truth diff、check-mode / dry-run evidence、rollback、"
        "post-apply verifier、KM / PlayBook writeback 與 0 / false 邊界。此端點不查 Wazuh API、"
        "不讀主機、不重新註冊 agent、不重啟服務、不保存機密、不啟用主動回應、不改 Nginx / "
        "Docker / K8s / firewall。"
    ),
)
async def get_iwooos_wazuh_runtime_gate_owner_review_readback() -> dict[str, Any]:
    """回傳 Wazuh runtime gate owner-review 公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_wazuh_runtime_gate_owner_review_readback
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh runtime gate owner-review readback 無效：{exc}",
        ) from exc


@router.post(
    "/api/v1/iwooos/wazuh-runtime-gate-owner-review-readback/validate-owner-review-packet",
    response_model=dict[str, Any],
    summary="驗證 Wazuh runtime gate 脫敏 owner-review packet",
    description=(
        "針對單次 owner / reviewer 提供的 redacted Wazuh runtime gate owner-review packet "
        "進行 no-persist readiness validation，回傳 accepted-for-readback / needs supplement / "
        "quarantined / rejected runtime action 分流。此端點不保存 payload、不查 Wazuh API、不讀主機、"
        "不重新註冊 agent、不重啟服務、不讀或回傳機密明文、不啟用主動回應、不改 Nginx / Docker / "
        "K8s / firewall，也不更新 runtime gate 總帳。"
    ),
)
async def validate_iwooos_wazuh_runtime_gate_owner_review_packet(
    owner_review_packet: dict[str, Any],
) -> dict[str, Any]:
    """回傳單次 Wazuh runtime gate owner-review packet 的公開安全驗證結果。"""
    try:
        payload = await asyncio.to_thread(
            validate_wazuh_runtime_gate_owner_review_packet_payload,
            owner_review_packet,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS Wazuh runtime gate owner-review packet 驗證器無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/runtime-security-readback",
    response_model=dict[str, Any],
    summary="取得 IwoooS runtime security readback",
    description=(
        "讀取最新已提交的 IwoooS 資安只讀快照，彙總 Wazuh、Kali、SOC/SIEM、"
        "告警可讀性、owner dispatch 與外部入侵防護 Gate，並附上 Wazuh 只讀路由的"
        "公開安全 aggregate 讀回。此端點不呼叫 Kali / 主機 / Docker / Nginx / firewall / "
        "Telegram，不保存 raw Wazuh payload，不收集 secret，不授權 runtime 寫入。"
    ),
)
async def get_iwooos_runtime_security_readback() -> dict[str, Any]:
    """回傳 IwoooS 資安 runtime readback 只讀總板。"""
    try:
        wazuh_result = await load_iwooos_wazuh_readonly_status()
        payload = await asyncio.to_thread(
            load_latest_iwooos_runtime_security_readback,
            wazuh_live_status=wazuh_result.payload,
            wazuh_live_http_status=wazuh_result.http_status,
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS runtime security readback 無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/security-control-coverage",
    response_model=dict[str, Any],
    summary="取得 IwoooS 資安納管覆蓋總表",
    description=(
        "彙整已提交的主機、產品、服務、配置、監控、Wazuh、AI Agent 與 agent-bounty "
        "資安納管 snapshot，形成只讀覆蓋總表。此端點不查 live host、不讀 secret、不啟動掃描、"
        "不送告警、不開 runtime gate。"
    ),
)
async def get_iwooos_security_control_coverage() -> dict[str, Any]:
    """回傳 IwoooS 資安納管覆蓋只讀總表。"""
    try:
        payload = await asyncio.to_thread(load_latest_iwooos_security_control_coverage)
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS security control coverage 無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/high-value-config-control-coverage",
    response_model=dict[str, Any],
    summary="取得 IwoooS 高價值配置控管覆蓋矩陣",
    description=(
        "讀取已提交的高價值配置控管 snapshot，回傳 Nginx、DNS / TLS、K8s、"
        "Secrets、runner、Firewall、Backup、AI provider 與 agent-bounty runtime 的"
        "公開安全只讀投影。此端點不查 live host、不讀 secret、不執行 nginx -t、"
        "不 reload、不 sync、不啟動掃描、不開 runtime gate。"
    ),
)
async def get_iwooos_high_value_config_control_coverage() -> dict[str, Any]:
    """回傳高價值配置控管矩陣公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_high_value_config_control_coverage
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS high-value config control coverage 無效：{exc}",
        ) from exc


@router.get(
    "/api/v1/iwooos/owner-evidence-intake-preflight",
    response_model=dict[str, Any],
    summary="取得 IwoooS 負責人脫敏證據收件預檢",
    description=(
        "整合 high-value config owner packet、配置覆蓋矩陣與 Wazuh 負責人證據預檢，"
        "回傳 Nginx、DNS / TLS、K8s、secret / runner、public runtime config 與 Wazuh registry "
        "的公開安全收件欄位、拒收規則與 0 / false 邊界。此端點不送 owner request、不收回覆、"
        "不寫 reviewer queue、不讀 secret、不查 live host、不查 Wazuh API、不啟動 runtime action。"
    ),
)
async def get_iwooos_owner_evidence_intake_preflight() -> dict[str, Any]:
    """回傳 IwoooS 負責人脫敏證據收件預檢公開安全只讀狀態。"""
    try:
        payload = await asyncio.to_thread(
            load_latest_iwooos_owner_evidence_intake_preflight
        )
        return redact_public_lan_topology(payload)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"IwoooS owner evidence intake preflight 無效：{exc}",
        ) from exc
