#!/usr/bin/env python3
"""Audit the native networking/client lifecycle milestone boundary."""

from __future__ import annotations

from pathlib import Path
import re

import generate_api_shims


ROOT = Path(__file__).resolve().parents[1]
OWNED_SOURCES = (
    "caps.rs",
    "caps_http.rs",
    "client_core.rs",
    "download_manager.rs",
    "event_queue.rs",
    "login.rs",
    "network_manager.rs",
    "sim_stats.rs",
    "udp_transport.rs",
)
REQUIRED_NATIVE_TYPES = {
    "T:LibreMetaverse.Caps",
    "T:LibreMetaverse.GridClient",
    "T:LibreMetaverse.Http.DownloadManager",
    "T:LibreMetaverse.Http.EventQueueClient",
    "T:LibreMetaverse.HttpCapsClient",
    "T:LibreMetaverse.NetworkManager",
    "T:LibreMetaverse.Settings",
    "T:LibreMetaverse.Simulator",
    "T:LibreMetaverse.Simulator.SimStats",
    "T:LibreMetaverse.UDPBase",
    "T:LibreMetaverse.UDPPacketBuffer",
}
STUB_RE = re.compile(r"\b(?:not_implemented|unimplemented_api)\b|\b(?:todo|unimplemented)!\s*\(")


def check_owned_sources() -> None:
    source_root = ROOT / "crates" / "libremetaverse" / "src"
    offenders = [
        name for name in OWNED_SOURCES if STUB_RE.search((source_root / name).read_text())
    ]
    if offenders:
        raise SystemExit("milestone 08 owned Rust stubs remain: " + ", ".join(offenders))


def check_native_mapping() -> None:
    native = generate_api_shims.NATIVE_TYPES.keys() | generate_api_shims.NATIVE_DECLARATIONS.keys()
    missing = sorted(REQUIRED_NATIVE_TYPES - native)
    if missing:
        raise SystemExit("milestone 08 native type mappings missing: " + ", ".join(missing))


def check_fake_grid_gate() -> None:
    tests = (ROOT / "crates" / "libremetaverse" / "tests" / "network_manager.rs").read_text()
    required_evidence = (
        "offline_fake_grid_drives_the_complete_networking_lifecycle_without_task_leaks",
        "EventQueueGet",
        "active_download_count",
        "dispatcher_running",
        "get_recv_packets",
        "get_sent_packets",
        "seed-secret",
        "queue-secret",
        "asset-secret",
    )
    missing = [marker for marker in required_evidence if marker not in tests]
    if missing:
        raise SystemExit("fake-grid audit evidence missing: " + ", ".join(missing))


def check_bounded_policies() -> None:
    expectations = {
        "caps_http.rs": ("CapsHttpLimits", "max_redirects", "max_response_bytes"),
        "download_manager.rs": ("DOWNLOAD_QUEUE_CAPACITY", "MAX_PARALLEL_DOWNLOADS"),
        "event_queue.rs": ("EventQueuePolicy", "max_events_per_response", "max_event_nodes"),
        "udp_transport.rs": (
            "UdpTransportConfig",
            "receive_queue_capacity",
            "command_queue_capacity",
            "write_queue_capacity",
        ),
    }
    source_root = ROOT / "crates" / "libremetaverse" / "src"
    for name, markers in expectations.items():
        source = (source_root / name).read_text()
        missing = [marker for marker in markers if marker not in source]
        if missing:
            raise SystemExit(f"{name}: bounded policy evidence missing: " + ", ".join(missing))


def main() -> None:
    check_owned_sources()
    check_native_mapping()
    check_fake_grid_gate()
    check_bounded_policies()
    print(
        "milestone 08 audit: native networking sources contain no stubs; "
        "fake-grid lifecycle, redaction, task cleanup, statistics, and bounded policies are present"
    )


if __name__ == "__main__":
    main()
