"""Dialog Studio – Autostart 24/7 (GPU-Render-Server im WLAN)."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TASK_NAME = "VidPulsDialogGPU"
STARTUP_BAT = "VidPuls-Dialog-GPU.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:
    return (
        Path.home()
        / "AppData"
        / "Roaming"
        / "Microsoft"
        / "Windows"
        / "Start Menu"
        / "Programs"
        / "Startup"
    )


def _server_cmd() -> str:
    script = ROOT / "scripts" / "dialog_studio_server.py"
    py = _pythonw()
    return f'"{py}" "{script}" --daemon'


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 \"\" {_server_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(*, firewall: bool = True) -> tuple[int, str]:
    logs: list[str] = []
    if firewall:
        try:
            from jam.dialog_shop import enable_lan_firewall

            ok, msg = enable_lan_firewall()
            logs.append(f"Firewall: {msg}" if ok else f"Firewall (Hinweis): {msg}")
        except Exception as e:
            logs.append(f"Firewall: {e}")

    script = ROOT / "scripts" / "dialog_studio_server.py"
    py = _pythonw()
    cmd = f'"{py}" "{script}" --daemon'
    subprocess.run(["schtasks", "/Delete", "/TN", TASK_NAME, "/F"], capture_output=True)
    r = subprocess.run(
        [
            "schtasks",
            "/Create",
            "/TN",
            TASK_NAME,
            "/TR",
            cmd,
            "/SC",
            "ONLOGON",
            "/RL",
            "HIGHEST",
            "/F",
        ],
        capture_output=True,
        text=True,
    )
    path = install_startup_folder()
    logs.append(f"Startup: {path}")
    if r.returncode == 0:
        logs.append("Task Scheduler: OK")
    else:
        msg = (r.stderr or r.stdout or "").strip()
        logs.append(f"Task Scheduler: {msg[:120]}")
    return 0, " · ".join(logs)


def remove_autostart() -> 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 "Autostart entfernt").strip()
