"""JamPulse AI – Autostart beim Windows-Login."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TASK_NAME = "JamPulseAI"
STARTUP_BAT = "JamPulse-AI-Autostart.bat"


def _pythonw() -> str:
    exe = Path(sys.executable)
    pyw = exe.with_name("pythonw.exe")
    return str(pyw if pyw.is_file() else exe)


def startup_folder() -> Path:
    appdata = Path.home() / "AppData" / "Roaming"
    return appdata / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"


def _autostart_cmd() -> str:
    script = ROOT / "scripts" / "pixverse_studio.py"
    py = _pythonw()
    return f'"{py}" "{script}" --daemon --no-open'


def install_startup_folder() -> Path:
    folder = startup_folder()
    folder.mkdir(parents=True, exist_ok=True)
    bat = folder / STARTUP_BAT
    bat.write_text(
        f"@echo off\r\nchcp 65001 >nul\r\ncd /d \"{ROOT}\"\r\nstart \"\" {_autostart_cmd()}\r\n",
        encoding="utf-8",
    )
    return bat


def remove_startup_folder() -> bool:
    bat = startup_folder() / STARTUP_BAT
    if bat.is_file():
        bat.unlink()
        return True
    return False


def install_autostart_task() -> tuple[int, str]:
    script = ROOT / "scripts" / "pixverse_studio.py"
    py = _pythonw()
    cmd = f'"{py}" "{script}" --daemon --no-open'
    subprocess.run(["schtasks", "/Delete", "/TN", TASK_NAME, "/F"], capture_output=True)
    r = subprocess.run(
        [
            "schtasks",
            "/Create",
            "/TN",
            TASK_NAME,
            "/TR",
            cmd,
            "/SC",
            "ONLOGON",
            "/RL",
            "LIMITED",
            "/F",
        ],
        capture_output=True,
        text=True,
    )
    msg = (r.stderr or r.stdout or "").strip()
    if r.returncode != 0:
        path = install_startup_folder()
        return 0, f"Startup-Ordner: {path} (Task Scheduler: {msg[:80]})"
    install_startup_folder()
    return r.returncode, msg


def remove_autostart_task() -> tuple[int, str]:
    remove_startup_folder()
    r = subprocess.run(
        ["schtasks", "/Delete", "/TN", TASK_NAME, "/F"],
        capture_output=True,
        text=True,
    )
    return r.returncode, (r.stderr or r.stdout or "").strip()
