from __future__ import annotations

import os
import platform
from pathlib import Path
from typing import Any


def ebpf_capabilities() -> dict[str, Any]:
    system = platform.system().lower()
    is_linux = system == "linux"
    inside_container = os.path.exists("/.dockerenv")
    bpffs = Path("/sys/fs/bpf").exists()
    tracing = Path("/sys/kernel/tracing").exists() or Path("/sys/kernel/debug/tracing").exists()
    docker_sock = Path("/var/run/docker.sock").exists()
    supported = bool(is_linux and bpffs and tracing)
    return {
        "ok": True,
        "supported": supported,
        "platform": system,
        "inside_container": inside_container,
        "bpffs_available": bpffs,
        "tracing_fs_available": tracing,
        "docker_socket_available": docker_sock,
        "recommended_mode": "sidecar" if inside_container else "host",
        "notes": [
            "eBPF monitoring is treated as Linux-only.",
            "Start with connect/egress events before file-open events.",
            "Prefer a privileged sidecar or host collector over embedding probes in the main Armorer app container.",
        ],
    }


def ebpf_plan() -> dict[str, Any]:
    caps = ebpf_capabilities()
    return {
        "ok": True,
        "capabilities": caps,
        "phases": [
            {
                "name": "Phase 1",
                "focus": "DB-backed history and OTEL/file ingestion",
                "status": "implemented",
            },
            {
                "name": "Phase 2",
                "focus": "Linux-only eBPF egress collector",
                "status": "planned",
                "events": ["connect", "dns (optional)", "container correlation"],
            },
            {
                "name": "Phase 3",
                "focus": "Selective file-access visibility",
                "status": "planned",
                "events": ["open/openat on monitored paths only"],
            },
        ],
        "collector_shape": {
            "deployment": "privileged sidecar or host collector",
            "ingest_target": "~/.armorer/armorer.db runtime_events table",
            "normalization": [
                "map cgroup/container id to Docker container",
                "map container to Armorer app alias",
                "emit normalized runtime_events rows",
            ],
        },
        "verification": [
            "generate outbound test traffic from a target container and verify runtime_events rows",
            "assert unsupported environments degrade cleanly without breaking Armorer",
            "load test event volume before enabling file-open probes",
        ],
    }
