"""VidPuls – WLAN-Freigabe (Firewall + Kunden-Links)."""

from __future__ import annotations

import subprocess
from pathlib import Path

DIALOG_PORT = 8793
STORYBOARD_PORT = 8795

PORT_RULES: dict[int, str] = {
    DIALOG_PORT: "VidPuls Dialog Studio LAN",
    STORYBOARD_PORT: "VidPuls Storyboard Studio LAN",
}


def local_ip() -> str:
    try:
        from jam.wan2gp_local import local_ip as _lip

        return _lip()
    except ImportError:
        return "127.0.0.1"


def enable_port_firewall(port: int, *, name: str | None = None) -> tuple[bool, str]:
    rule = name or PORT_RULES.get(port) or f"VidPuls Port {port} LAN"
    try:
        subprocess.run(
            ["netsh", "advfirewall", "firewall", "delete", "rule", f"name={rule}"],
            capture_output=True,
            timeout=30,
        )
        r = subprocess.run(
            [
                "netsh",
                "advfirewall",
                "firewall",
                "add",
                "rule",
                f"name={rule}",
                "dir=in",
                "action=allow",
                "protocol=TCP",
                f"localport={port}",
            ],
            capture_output=True,
            text=True,
            timeout=30,
        )
        if r.returncode == 0:
            return True, f"Port {port} freigegeben ({rule})."
        err = (r.stderr or r.stdout or "netsh fehlgeschlagen")[:300]
        if "Zugriff verweigert" in err or "elevated" in err.lower():
            return False, "Admin-Rechte nötig – VidPuls LAN für alle.bat als Administrator ausführen."
        return False, err
    except (subprocess.SubprocessError, OSError) as e:
        return False, str(e)


def open_all_lan_ports() -> list[dict]:
    results: list[dict] = []
    for port, name in PORT_RULES.items():
        ok, msg = enable_port_firewall(port, name=name)
        results.append({"port": port, "ok": ok, "message": msg, "name": name})
    return results


def lan_urls() -> dict[str, str]:
    ip = local_ip()
    return {
        "ip": ip,
        "dialog": f"http://{ip}:{DIALOG_PORT}/",
        "storyboard": f"http://{ip}:{STORYBOARD_PORT}/",
        "dialog_local": f"http://127.0.0.1:{DIALOG_PORT}/",
        "storyboard_local": f"http://127.0.0.1:{STORYBOARD_PORT}/",
    }


def write_lan_links_file() -> Path:
    try:
        from jam.jampulse_desktop import studio_root

        base = studio_root()
    except ImportError:
        base = Path.home() / "Desktop" / "VidPuls"
        base.mkdir(parents=True, exist_ok=True)

    urls = lan_urls()
    text = (
        "VidPuls – Links für alle im WLAN\n"
        f"{'=' * 42}\n\n"
        f"Deine PC-IP: {urls['ip']}\n\n"
        "An Freunde / Kunden senden:\n\n"
        f"  Dialog Studio (3D Dating + Shop):\n"
        f"    {urls['dialog']}\n\n"
        f"  Storyboard Studio (Pollo-Style KI-Video):\n"
        f"    {urls['storyboard']}\n\n"
        "Nur auf diesem PC:\n"
        f"  {urls['dialog_local']}\n"
        f"  {urls['storyboard_local']}\n\n"
        "Hinweis: PC muss an sein. Storyboard nutzt deine API-Keys (Kosten).\n"
        "Dialog Studio: Zeitpass / Shop im WLAN.\n"
    )
    dest = base / "WLAN-LINKS.txt"
    dest.write_text(text, encoding="utf-8")
    return dest
