from __future__ import annotations

import subprocess
from typing import TypedDict

from k1link.artifacts import utc_now_iso


class CommandRecord(TypedDict):
    argv: list[str]
    returncode: int | None
    stdout: str
    stderr: str
    error: str | None


class NetworkSnapshot(TypedDict):
    schema_version: int
    created_at_utc: str
    sensitivity: str
    commands: list[CommandRecord]


def command_record(argv: list[str]) -> CommandRecord:
    try:
        result = subprocess.run(
            argv,
            check=False,
            capture_output=True,
            text=True,
            timeout=10,
        )
    except (OSError, subprocess.SubprocessError) as exc:
        return {
            "argv": argv,
            "returncode": None,
            "stdout": "",
            "stderr": "",
            "error": f"{type(exc).__name__}: {exc}",
        }
    return {
        "argv": argv,
        "returncode": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr,
        "error": None,
    }


def snapshot() -> NetworkSnapshot:
    """Collect a local read-only network snapshot; no packets are transmitted intentionally."""
    commands = [
        ["route", "-n", "get", "default"],
        ["networksetup", "-listallhardwareports"],
        ["scutil", "--nwi"],
        ["arp", "-an"],
    ]
    return {
        "schema_version": 1,
        "created_at_utc": utc_now_iso(),
        "sensitivity": (
            "contains local interface, route, IP/MAC and neighbor metadata; do not commit"
        ),
        "commands": [command_record(command) for command in commands],
    }
