"""
StartupService - Windows Registry autostart management.
"""
from __future__ import annotations

import sys
from pathlib import Path

from loguru import logger

from .base_service import BaseService

STARTUP_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
APP_NAME = "VoxCast"


class StartupService(BaseService):
    def __init__(self) -> None:
        self._ready = False

    async def start(self) -> None:
        self._ready = True
        logger.info("StartupService started, autostart={}", self.is_autostart_enabled())

    async def stop(self) -> None:
        self._ready = False

    def _get_autostart_command(self) -> str:
        """Return the full registry value for autostart, with proper quoting."""
        if getattr(sys, "frozen", False):
            # Nuitka build - single quoted exe path
            return f'"{Path(sys.argv[0]).resolve()}"'
        # Dev mode - quoted python + quoted script
        main_py = str(Path(__file__).resolve().parent.parent / "main.py")
        return f'"{sys.executable}" "{main_py}"'

    def enable_autostart(self) -> bool:
        try:
            import winreg
            command = self._get_autostart_command()
            with winreg.OpenKey(
                winreg.HKEY_CURRENT_USER, STARTUP_KEY, 0, winreg.KEY_SET_VALUE
            ) as key:
                winreg.SetValueEx(key, APP_NAME, 0, winreg.REG_SZ, command)
            logger.info("Autostart enabled: {}", command)
            return True
        except PermissionError:
            logger.warning("No permission to set autostart registry key")
            return False
        except Exception as e:
            logger.error("Failed to enable autostart: {}", e)
            return False

    def disable_autostart(self) -> bool:
        try:
            import winreg
            with winreg.OpenKey(
                winreg.HKEY_CURRENT_USER, STARTUP_KEY, 0, winreg.KEY_SET_VALUE
            ) as key:
                try:
                    winreg.DeleteValue(key, APP_NAME)
                except FileNotFoundError:
                    pass  # Already removed
            logger.info("Autostart disabled")
            return True
        except Exception as e:
            logger.error("Failed to disable autostart: {}", e)
            return False

    def is_autostart_enabled(self) -> bool:
        try:
            import winreg
            with winreg.OpenKey(
                winreg.HKEY_CURRENT_USER, STARTUP_KEY, 0, winreg.KEY_READ
            ) as key:
                try:
                    winreg.QueryValueEx(key, APP_NAME)
                    return True
                except FileNotFoundError:
                    return False
        except Exception:
            return False

    @property
    def is_ready(self) -> bool:
        return self._ready
