from __future__ import annotations

import getpass
import os
import platform
import socket
import sys
import time
import uuid
from typing import Any, Dict, Optional

from auditwalk.core.results_schema import PreflightResult, prls_from_signals, utc_now_iso


def _is_admin_best_effort() -> Optional[bool]:
    try:
        if os.name == "nt":
            import ctypes

            return bool(ctypes.windll.shell32.IsUserAnAdmin())
        return os.geteuid() == 0  # type: ignore[attr-defined]
    except Exception:
        return None


def _boot_time_epoch_best_effort() -> Optional[int]:
    try:
        return None
    except Exception:
        return None


def run_preflight() -> PreflightResult:
    run_id = f"pf_{uuid.uuid4().hex[:12]}"
    host = {
        "hostname": socket.gethostname(),
        "user": getpass.getuser(),
        "platform": platform.platform(),
        "python": sys.version.split()[0],
        "pid": os.getpid(),
    }
    signals: Dict[str, Any] = {
        "is_admin": _is_admin_best_effort(),
        "os_name": os.name,
        "machine": platform.machine(),
        "processor": platform.processor(),
        "boot_time_epoch": _boot_time_epoch_best_effort(),
        "now_epoch": int(time.time()),
    }
    prls = prls_from_signals(signals)
    return PreflightResult(
        kind="preflight",
        version="1",
        run_id=run_id,
        created_at=utc_now_iso(),
        host=host,
        signals=signals,
        prls=prls,
    )
