import logging
import subprocess
from pathlib import Path

from planemapper.provisioning import ProvisioningError

log = logging.getLogger(__name__)

_HOSTAPD_CONF_PATH = Path("/etc/hostapd/hostapd.conf")
_HOSTAPD_CONF = """\
interface=wlan0
driver=nl80211
ssid=planeMapper-setup
hw_mode=g
channel=6
wmm_enabled=0
auth_algs=1
ignore_broadcast_ssid=0
"""


def _write_hostapd_conf() -> None:
    _HOSTAPD_CONF_PATH.parent.mkdir(parents=True, exist_ok=True)
    _HOSTAPD_CONF_PATH.write_text(_HOSTAPD_CONF)


def start_ap() -> None:
    _write_hostapd_conf()
    result = subprocess.run(["hostapd", str(_HOSTAPD_CONF_PATH)], check=False)
    if result.returncode != 0:
        log.error("hostapd failed with return code %d", result.returncode)
        raise ProvisioningError(f"hostapd failed: returncode={result.returncode}")
    result = subprocess.run(
        ["dnsmasq", "--no-daemon", "--address=/#/192.168.4.1"],
        check=False,
    )
    if result.returncode != 0:
        log.error("dnsmasq failed with return code %d", result.returncode)
        raise ProvisioningError(f"dnsmasq failed: returncode={result.returncode}")
    log.info("AP started: SSID=planeMapper-setup")


def stop_ap() -> None:
    subprocess.run(["pkill", "-f", "hostapd"], check=False)
    subprocess.run(["pkill", "-f", "dnsmasq"], check=False)
    log.info("AP stopped")


def kill_wifi() -> None:
    result = subprocess.run(["rfkill", "block", "wifi"], check=False)
    if result.returncode != 0:
        log.error("rfkill failed with return code %d", result.returncode)
        raise ProvisioningError(f"rfkill failed: returncode={result.returncode}")
    log.info("WiFi radio killed")


def join_home_wifi(ssid: str, password: str) -> None:
    result = subprocess.run(
        ["nmcli", "device", "wifi", "connect", ssid, "password", password],
        capture_output=True,
        timeout=30,
        check=False,
    )
    if result.returncode != 0:
        log.error("nmcli failed (rc=%d): %s", result.returncode, result.stderr.decode())
        raise ProvisioningError(f"nmcli failed (rc={result.returncode}): {result.stderr.decode()}")
    log.info("joined home WiFi: %s", ssid)
