from __future__ import annotations

import os
import sys
from pathlib import Path

from .paths import user_data_dir

APP_RUN_NAME = "TiHiY Voice Translator"


def _pythonw_executable() -> str:
    exe = Path(sys.executable)
    if os.name == "nt" and exe.name.lower() == "python.exe":
        candidate = exe.with_name("pythonw.exe")
        if candidate.exists():
            return str(candidate)
    return str(exe)


def _launcher_path() -> Path:
    return user_data_dir() / "start_background.cmd"


def _write_source_launcher() -> Path:
    project_root = Path(__file__).resolve().parents[2]
    launcher = _launcher_path()
    launcher.write_text(
        "@echo off\r\n"
        f'cd /d "{project_root}"\r\n'
        f'start "" /b "{_pythonw_executable()}" -m app.main --background\r\n',
        encoding="utf-8",
    )
    return launcher


def startup_command() -> str:
    if getattr(sys, "frozen", False):
        return f'"{Path(sys.executable)}" --background'
    launcher = _write_source_launcher()
    return f'cmd.exe /d /c ""{launcher}""'


def set_start_with_windows(enabled: bool) -> None:
    if os.name != "nt":
        return
    import winreg

    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE) as key:
        if enabled:
            winreg.SetValueEx(key, APP_RUN_NAME, 0, winreg.REG_SZ, startup_command())
        else:
            try:
                winreg.DeleteValue(key, APP_RUN_NAME)
            except FileNotFoundError:
                pass
            try:
                _launcher_path().unlink()
            except FileNotFoundError:
                pass


def is_start_with_windows_enabled() -> bool:
    if os.name != "nt":
        return False
    import winreg

    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_READ) as key:
            winreg.QueryValueEx(key, APP_RUN_NAME)
            return True
    except FileNotFoundError:
        return False
