"""Jam-Sprache & Steuerung für Discord-Bot."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from jam.brain import JamBrain
from jam.discord_setup import (
    CONFIG_FILE,
    PID_FILE,
    deploy_home,
    is_bot_running,
    load_config,
    setup_discord,
)

ROOT = Path(__file__).resolve().parent.parent
RUN_SCRIPT = ROOT / "scripts" / "run_discord_bot.py"


def hears_discord(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "discord" not in h:
        return False
    return any(
        w in h
        for w in (
            "einricht",
            "setup",
            "bot",
            "skript",
            "script",
            "server",
            "start",
            "stopp",
            "stop",
            "befehl",
            "command",
        )
    )


def start_bot_process() -> str:
    cfg = load_config()
    if not (cfg.get("token") or "").strip():
        return (
            f"Kein Token in {CONFIG_FILE.name}. "
            "Sag „Discord einrichten“ – dann Token vom Developer Portal eintragen."
        )
    if is_bot_running():
        return "Discord-Bot läuft schon."

    deploy_home()
    RUN_SCRIPT.parent.mkdir(parents=True, exist_ok=True)
    creationflags = 0
    if sys.platform == "win32":
        creationflags = subprocess.CREATE_NO_WINDOW  # type: ignore[attr-defined]

    proc = subprocess.Popen(
        [sys.executable, str(RUN_SCRIPT)],
        cwd=str(ROOT),
        creationflags=creationflags,
    )
    PID_FILE.parent.mkdir(parents=True, exist_ok=True)
    PID_FILE.write_text(str(proc.pid), encoding="utf-8")
    return f"Discord-Bot gestartet (PID {proc.pid}). Im Channel: !jam !ping !scripts"


def stop_bot_process() -> str:
    if not PID_FILE.is_file():
        return "Discord-Bot war nicht gestartet."
    try:
        import os

        pid = int(PID_FILE.read_text(encoding="utf-8").strip())
        os.kill(pid, 9)
    except (OSError, ValueError):
        pass
    PID_FILE.unlink(missing_ok=True)
    return "Discord-Bot gestoppt."


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_discord(heard):
        return None
    h = heard.lower()

    if any(w in h for w in ("stopp", "stop", "aus")):
        brain.state.last_action = "discord_stop"
        brain.save()
        return stop_bot_process()

    if any(w in h for w in ("start", "starte", "lauf", "an")):
        brain.state.last_action = "discord_start"
        brain.save()
        return start_bot_process()

    if any(w in h for w in ("einricht", "setup", "erstell", "konfigur")):
        msg = setup_discord(brain)
        return msg

    return (
        setup_discord(brain, open_browser=False)
        + " Zum Starten: „Discord Bot starten“. Skripte: !ping !shop in discord_scripts/"
    )
