"""
Auto-start functionality for BLE daemon.
"""

import os
import subprocess
import sys
import time
from typing import Optional

from airctl.common.logging import get_logger
from airctl.common.platform import is_windows
from airctl.ipc.transport import get_default_socket_path, get_pid_file_path

logger = get_logger(__name__)


def ensure_daemon_running(log_level: str = "INFO") -> int:
    """
    Ensure the daemon is running, starting it if necessary.

    Args:
        log_level: Log level for daemon

    Returns:
        Daemon PID

    Raises:
        RuntimeError: If daemon fails to start
    """
    from airctl.ipc.client import DaemonClient

    client = DaemonClient()

    if client.is_running():
        pid = client.get_pid()
        if pid:
            logger.debug(f"Daemon already running (PID: {pid})")
            return pid

    _cleanup_stale_daemon()

    logger.info("Starting BLE daemon...")

    pid = _start_daemon_process(log_level=log_level)

    max_wait = 20
    for i in range(max_wait):
        time.sleep(0.5)
        if client.is_running():
            logger.info(f"Daemon started (PID: {pid})")
            return pid

    raise RuntimeError("Failed to start daemon")


def _cleanup_stale_daemon() -> None:
    """Clean up stale daemon resources."""
    pid_file = get_pid_file_path()
    if os.path.exists(pid_file):
        try:
            os.remove(pid_file)
            logger.debug(f"Removed stale PID file: {pid_file}")
        except Exception as e:
            logger.warning(f"Failed to remove stale PID file: {e}")


def _start_daemon_process(log_level: str = "INFO") -> int:
    """
    Start the daemon process.

    Args:
        log_level: Log level for daemon

    Returns:
        PID of started process
    """
    module_path = "airctl.daemon"

    if is_windows():
        creationflags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
        stdin = subprocess.DEVNULL
        stdout = subprocess.DEVNULL
        stderr = subprocess.DEVNULL
    else:
        creationflags = 0
        stdin = subprocess.DEVNULL
        stdout = subprocess.DEVNULL
        stderr = subprocess.DEVNULL

    process = subprocess.Popen(
        [sys.executable, "-m", module_path, "--log-level", log_level],
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        creationflags=creationflags,
        close_fds=True,
    )

    return process.pid


def stop_daemon() -> bool:
    """
    Stop the daemon if running.

    Returns:
        True if daemon was stopped, False if not running
    """
    from airctl.ipc.client import DaemonClient

    client = DaemonClient()

    if not client.is_running():
        return True

    return client.stop_daemon()


def get_daemon_status() -> dict:
    """
    Get daemon status.

    Returns:
        Dict with 'running' and 'pid' keys
    """
    from airctl.ipc.client import DaemonClient

    client = DaemonClient()

    if client.is_running():
        return {
            "running": True,
            "pid": client.get_pid(),
        }
    else:
        return {
            "running": False,
            "pid": None,
        }


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="BLE Daemon")
    parser.add_argument(
        "--log-level",
        default="INFO",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        help="Log level",
    )
    args = parser.parse_args()

    from airctl.daemon.server import run_daemon

    run_daemon(log_level=args.log_level)
