"""Direct guest-network validation for a curated environment."""

from __future__ import annotations

import argparse
from dataclasses import dataclass
from pathlib import Path

from pyro_mcp.api import Pyro

NETWORK_CHECK_COMMAND = (
    'python3 -c "import urllib.request as u; '
    "print(u.urlopen('https://example.com').status)"
    '"'
)


@dataclass(frozen=True)
class NetworkCheckResult:
    vm_id: str
    execution_mode: str
    network_enabled: bool
    exit_code: int
    stdout: str
    stderr: str
    cleanup: dict[str, object]


def run_network_check(
    *,
    environment: str = "debian:12",
    vcpu_count: int = 1,
    mem_mib: int = 1024,
    ttl_seconds: int = 600,
    timeout_seconds: int = 120,
    base_dir: Path | None = None,
) -> NetworkCheckResult:  # pragma: no cover - integration helper
    pyro = Pyro(base_dir=base_dir)
    result = pyro.run_in_vm(
        environment=environment,
        command=NETWORK_CHECK_COMMAND,
        vcpu_count=vcpu_count,
        mem_mib=mem_mib,
        timeout_seconds=timeout_seconds,
        ttl_seconds=ttl_seconds,
        network=True,
    )
    return NetworkCheckResult(
        vm_id=str(result["vm_id"]),
        execution_mode=str(result["execution_mode"]),
        network_enabled=True,
        exit_code=int(result["exit_code"]),
        stdout=str(result["stdout"]),
        stderr=str(result["stderr"]),
        cleanup=dict(result["cleanup"]),
    )


def main() -> None:  # pragma: no cover - CLI wiring
    parser = argparse.ArgumentParser(description="Run a guest networking check.")
    parser.add_argument("--environment", default="debian:12")
    parser.add_argument("--vcpu-count", type=int, default=1)
    parser.add_argument("--mem-mib", type=int, default=1024)
    parser.add_argument("--ttl-seconds", type=int, default=600)
    parser.add_argument("--timeout-seconds", type=int, default=120)
    args = parser.parse_args()

    result = run_network_check(
        environment=args.environment,
        vcpu_count=args.vcpu_count,
        mem_mib=args.mem_mib,
        ttl_seconds=args.ttl_seconds,
        timeout_seconds=args.timeout_seconds,
    )
    print(f"[network] vm_id={result.vm_id}")
    print(f"[network] execution_mode={result.execution_mode}")
    print(f"[network] network_enabled={result.network_enabled}")
    print(f"[network] exit_code={result.exit_code}")
    if result.exit_code == 0 and result.stdout.strip() == "200":
        print("[network] result=success")
        return
    print("[network] result=failure")
    if result.stdout.strip():
        print(f"[network] stdout={result.stdout.strip()}")
    if result.stderr.strip():
        print(f"[network] stderr={result.stderr.strip()}")
    raise SystemExit(1)
