"""Step 1: Pre-flight checks — root/sudo, OS, curl/git, disk space, network."""

from __future__ import annotations

from easyclaw_tui.steps.base import BaseStep, StepResult


class PreflightStep(BaseStep):
    STEP_NUM = 1
    STEP_NAME = "Pre-flight"

    async def run(self) -> StepResult:
        # Root check
        rc, out, _ = await self.run_cmd("id -u")
        if out == "0":
            self.ok("Running as root")
            self.state.use_sudo = False
        else:
            if await self.cmd_ok("command -v sudo"):
                self.info("Running with sudo")
                self.state.use_sudo = True
            else:
                return StepResult(False, message="Must be run as root or with sudo")

        # OS check
        rc, out, _ = await self.run_cmd("cat /etc/os-release 2>/dev/null | grep ^PRETTY_NAME | cut -d'\"' -f2")
        if out:
            self.state.os_name = out
            self.ok(f"OS: {out}")
        else:
            self.warn("Cannot detect OS — proceeding anyway")

        # Check ID for ubuntu/debian
        _, distro, _ = await self.run_cmd("cat /etc/os-release 2>/dev/null | grep ^ID= | cut -d'=' -f2")
        if distro and distro not in ("ubuntu", "debian"):
            self.warn(f"Tested on Ubuntu/Debian. Your OS: {distro} — proceed with caution.")

        # Required commands
        for cmd in ("curl", "git"):
            if await self.cmd_ok(f"command -v {cmd}"):
                self.ok(f"{cmd} found")
            else:
                self.info(f"Installing {cmd}...")
                await self.run_cmd(self.sudo("apt-get update -qq && apt-get install -y -qq " + cmd))
                if await self.cmd_ok(f"command -v {cmd}"):
                    self.ok(f"{cmd} installed")
                else:
                    return StepResult(False, message=f"Failed to install {cmd}")

        # Disk space
        _, disk_out, _ = await self.run_cmd("df -m / | awk 'NR==2 {print $4}'")
        try:
            free_mb = int(disk_out)
            if free_mb < 2000:
                return StepResult(False, message=f"Insufficient disk space: {free_mb}MB free (need 2GB+)")
            self.ok(f"Disk: {free_mb}MB free")
        except ValueError:
            self.warn("Could not check disk space")

        # Network
        if await self.cmd_ok("curl -sf --max-time 10 https://easyclaw.help/health"):
            self.ok("Network: can reach easyclaw.help")
        else:
            self.warn("Cannot reach easyclaw.help — check network connectivity")

        # VPS IP
        ip = await self.cmd_output("hostname -I 2>/dev/null | awk '{print $1}'")
        if ip:
            self.state.vps_ip = ip

        return StepResult(True)
