"""
Discord-Server & Bot einrichten – Ordner, Skripte, Konfiguration (alles selbst geschrieben).
"""

from __future__ import annotations

import json
import shutil
import time
import webbrowser
from pathlib import Path

from jam.brain import JamBrain

ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
CONFIG_FILE = DATA_DIR / "discord_config.json"
REGISTRY_FILE = DATA_DIR / "discord_scripts.json"
PID_FILE = DATA_DIR / "discord_bot.pid"
HOME = Path.home() / "Documents" / "Jam-Discord"
PROJECT_SCRIPTS = ROOT / "discord_scripts"

DEVELOPER_PORTAL = "https://discord.com/developers/applications"
INVITE_PERMISSIONS = "2147567616"  # Send Messages, Read History, Use Slash, Manage Roles light


def load_config() -> dict:
    if not CONFIG_FILE.is_file():
        return {}
    try:
        return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {}


def save_config(cfg: dict) -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    cfg["updated_at"] = time.time()
    CONFIG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")


def default_config() -> dict:
    return {
        "token": "",
        "command_prefix": "!",
        "guild_id": "",
        "admin_user_ids": [],
        "scripts_dir": str(HOME / "scripts"),
        "scripts_registry": str(REGISTRY_FILE),
        "client_id": "",
    }


def deploy_home(*, owner: str = "David") -> Path:
    """Kopiert Bot + Skripte nach Documents/Jam-Discord."""
    HOME.mkdir(parents=True, exist_ok=True)
    scripts_dst = HOME / "scripts"
    scripts_dst.mkdir(parents=True, exist_ok=True)

    if PROJECT_SCRIPTS.is_dir():
        for py in PROJECT_SCRIPTS.glob("*.py"):
            shutil.copy2(py, scripts_dst / py.name)

    if REGISTRY_FILE.is_file():
        shutil.copy2(REGISTRY_FILE, HOME / "scripts.json")

    runner_src = ROOT / "scripts" / "run_discord_bot.py"
    if runner_src.is_file():
        shutil.copy2(runner_src, HOME / "run_bot.py")

    (HOME / "EINRICHTUNG.md").write_text(
        f"# Discord einrichten – Jam für {owner}\n\n"
        "## 1. Discord Developer Portal\n"
        f"- Öffne: {DEVELOPER_PORTAL}\n"
        "- **New Application** → Name z. B. „Jam Bot“\n"
        "- **Bot** → Reset Token → Token in `data/discord_config.json` bei `token` eintragen\n"
        "- **Privileged Gateway Intents**: MESSAGE CONTENT INTENT aktivieren\n\n"
        "## 2. Bot einladen\n"
        "- OAuth2 → URL Generator → Scopes: `bot`, `applications.commands`\n"
        "- Permissions: Send Messages, Read Message History\n"
        "- Link auf deinem Server öffnen\n\n"
        "## 3. Server-Struktur (Vorschlag)\n"
        "- `#bot-befehle` – nur Bot + Admins\n"
        "- `#minecraft` – Server-News\n"
        "- `#shop` – Jam-Shop Link\n\n"
        "## 4. Skripte\n"
        "Neue `.py` Dateien in `scripts/` legen und in `scripts.json` eintragen:\n"
        "```json\n"
        '{"id": "meins", "file": "meins.py", "discord_command": "meins", "admin_only": false}\n'
        "```\n\n"
        "## 5. Bot starten\n"
        "- Doppelklick: `start-discord-bot.bat` im jam-buddy Ordner\n"
        "- Oder Jam sagen: **„Discord Bot starten“**\n\n"
        "## Befehle im Discord\n"
        "- `!scripts` – alle registrierten Skripte\n"
        "- `!ping` / `!shop` / `!info` – Skript ausführen\n"
        "- `!run <id>` – Skript per ID (Admins bei admin_only)\n"
        "- `!jam` – Hilfe\n\n"
        "Alles **selbst geschrieben** – kein fremdes Bot-Framework außer discord.py-Bibliothek.\n",
        encoding="utf-8",
    )
    return HOME


def setup_discord(brain: JamBrain | None = None, *, open_browser: bool = True) -> str:
    owner = brain.state.owner_name if brain else "David"
    home = deploy_home(owner=owner)
    cfg = load_config()
    if not cfg:
        cfg = default_config()
    cfg["scripts_dir"] = str(home / "scripts")
    cfg["scripts_registry"] = str(REGISTRY_FILE)
    save_config(cfg)

    if open_browser:
        try:
            webbrowser.open(DEVELOPER_PORTAL, new=2)
            webbrowser.open("https://discord.com/channels/@me", new=2)
        except OSError:
            pass

    if brain:
        setattr(brain.state, "discord_setup_done", True)
        brain.state.last_action = "discord_setup"
        brain.state.remember(f"Discord eingerichtet: {home}")
        brain.save()

    return (
        f"Discord eingerichtet! Ordner: {home}. "
        f"Token in {CONFIG_FILE.name} eintragen, dann „Discord Bot starten“. "
        "Befehle: !ping !shop !info !scripts !run"
    )


def is_bot_running() -> bool:
    if not PID_FILE.is_file():
        return False
    try:
        import os

        pid = int(PID_FILE.read_text(encoding="utf-8").strip())
        os.kill(pid, 0)
        return True
    except (OSError, ValueError):
        return False
