from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from .paths import app_data_dir

TASK_NAME = "ProxyChainManagerAutoStart"


def _write_launcher_cmd() -> Path:
    """Create a stable launcher script so Task Scheduler does not need fragile quoting."""
    if getattr(sys, "frozen", False):
        exe = Path(sys.executable).resolve()
        body = f'@echo off\r\nstart "" /B "{exe}"\r\n'
    else:
        py = Path(sys.executable).resolve()
        if py.name.lower() == "python.exe":
            cand = py.with_name("pythonw.exe")
            if cand.is_file():
                py = cand
        root = Path(__file__).resolve().parent.parent
        run_py = (root / "run.py").resolve()
        body = f'@echo off\r\n"{py}" "{run_py}"\r\n'

    p = app_data_dir() / "launch_proxy_chain_manager.cmd"
    p.write_text(body, encoding="utf-8")
    return p


def install_logon_task() -> tuple[bool, str]:
    launcher = _write_launcher_cmd()
    tr = str(launcher)
    try:
        r = subprocess.run(
            [
                "schtasks",
                "/Create",
                "/F",
                "/TN",
                TASK_NAME,
                "/TR",
                tr,
                "/SC",
                "ONLOGON",
                "/RL",
                "LIMITED",
            ],
            capture_output=True,
            text=True,
            timeout=60,
        )
        out = (r.stdout or "") + (r.stderr or "")
        return r.returncode == 0, out.strip() or ("OK" if r.returncode == 0 else "Failed")
    except Exception as e:
        return False, str(e)


def uninstall_logon_task() -> tuple[bool, str]:
    try:
        r = subprocess.run(
            ["schtasks", "/Delete", "/F", "/TN", TASK_NAME],
            capture_output=True,
            text=True,
            timeout=60,
        )
        out = (r.stdout or "") + (r.stderr or "")
        return r.returncode == 0, out.strip() or ("OK" if r.returncode == 0 else "Failed")
    except Exception as e:
        return False, str(e)


def task_exists() -> bool:
    try:
        r = subprocess.run(
            ["schtasks", "/Query", "/TN", TASK_NAME],
            capture_output=True,
            text=True,
            timeout=30,
        )
        return r.returncode == 0
    except Exception:
        return False
