"""JamPulse AI – Desktop-Ordner, Starter, Video-Ausgabe."""

from __future__ import annotations

import json
from pathlib import Path

from jam.earn_report import desktop_folder
from jam.jampulse_brand import BRAND, MODULES, PRODUCT_BRAND, TAGLINE

ROOT = Path(__file__).resolve().parents[1]
DESKTOP = desktop_folder()
AI_ROOT = DESKTOP / "VidPuls"
VIDEOS_FRAME = AI_ROOT / "Videos" / "Frame"
VIDEOS_MINUTE = AI_ROOT / "Videos" / "Minute"
HTML_DESKTOP = DESKTOP / "VidPuls.html"


def _bat(name: str, cmd: str, *, admin: bool = False, dest_dir: Path | None = None) -> Path:
    base = dest_dir if dest_dir is not None else AI_ROOT
    p = base / name
    tail = f"{cmd}\r\n"
    if admin:
        tail += "echo.\r\npause\r\n"
        body = (
            f"@echo off\r\nchcp 65001 >nul\r\ncd /d \"{ROOT}\"\r\n"
            f"net session >nul 2>&1\r\n"
            f"if errorlevel 1 (\r\n"
            f"  powershell -NoProfile -Command \"Start-Process -FilePath '%~f0' -Verb RunAs\"\r\n"
            f"  exit /b\r\n"
            f")\r\n"
            f"{tail}"
        )
    else:
        body = f"@echo off\r\nchcp 65001 >nul\r\ncd /d \"{ROOT}\"\r\n{tail}"
    base.mkdir(parents=True, exist_ok=True)
    p.write_text(body, encoding="utf-8")
    return p


def launcher_html() -> str:
    modules = "".join(
        f'<li><strong>{m["name"]}</strong> – {m["role"]}</li>' for m in MODULES.values()
    )
    return f"""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{PRODUCT_BRAND}</title>
<style>
  body{{font-family:Segoe UI,sans-serif;background:#07050f;color:#f1ecff;max-width:520px;margin:2rem auto;padding:1rem}}
  h1{{background:linear-gradient(90deg,#a855f7,#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent}}
  .card{{background:#12101f;border:1px solid rgba(168,85,247,.35);border-radius:16px;padding:1.25rem;margin:1rem 0}}
  code{{background:#0c0a16;padding:.2rem .45rem;border-radius:6px;font-size:.85rem}}
  ul{{line-height:1.8;color:#9ca3af}}
  p{{color:#9ca3af;line-height:1.55}}
</style>
</head>
<body>
  <h1>{PRODUCT_BRAND}</h1>
  <p>{TAGLINE}</p>
  <div class="card">
    <p><strong>Ordner auf dem Desktop:</strong><br><code>VidPuls\\</code></p>
    <ul>
      <li><code>Dialog Produktion einrichten.bat</code> – alles auf einmal (Config, Firewall, Server)</li>
      <li><code>Dialog GPU Server 24-7.bat</code> – Shop + GPU-Render dauerhaft (PC an lassen)</li>
      <li><code>Dialog GPU Autostart einrichten.bat</code> – startet bei Windows-Login</li>
      <li><code>Dialog Shop LAN starten.bat</code> – Shop für Freunde im WLAN</li>
      <li><code>Dialog LAN Firewall.bat</code> – Port 8793 freigeben</li>
      <li><code>VidPuls LAN für alle.bat</code> – Ports 8793 + 8795 für WLAN (Admin)</li>
      <li><code>Dialog Werbung exportieren.bat</code> – Preise &amp; PayPal-Links</li>
      <li><code>Dialog Studio starten.bat</code> – Dating-Dialog (Sarah &amp; Laura)</li>
      <li><code>Storyboard Studio starten.bat</code> – Pollo-Style (GPT Image + Seedance)</li>
      <li><code>Wan2GP Studio starten.bat</code> – lokales KI-Video (Wan/LTX, 0 €)</li>
      <li><code>Wan2GP einrichten.bat</code> – Pinokio + AMD Setup</li>
      <li><code>Frame starten.bat</code> – KI-Video Cloud (Prompt/Bild)</li>
      <li><code>Minute starten.bat</code> – 60-Sek.-Video aus Prompt</li>
      <li><code>JamPulse Menü.bat</code> – alles in einem Menü</li>
      <li><code>Autopilot.bat</code> – Deploy + Crons</li>
    </ul>
    <p>Videos: <code>VidPuls\\Videos\\Frame</code>, <code>…\\Minute</code>, <code>…\\Storyboard</code></p>
  </div>
  <div class="card">
    <p><strong>Module</strong></p>
    <ul>{modules}</ul>
  </div>
</body>
</html>"""


def ai_root() -> Path:
    return desktop_folder() / "VidPuls"


def videos_minute_dir() -> Path:
    p = ai_root() / "Videos" / "Minute"
    p.mkdir(parents=True, exist_ok=True)
    return p


def videos_frame_dir() -> Path:
    p = ai_root() / "Videos" / "Frame"
    p.mkdir(parents=True, exist_ok=True)
    return p


def videos_storyboard_dir() -> Path:
    p = ai_root() / "Videos" / "Storyboard"
    p.mkdir(parents=True, exist_ok=True)
    return p


def studio_root() -> Path:
    p = ai_root()
    p.mkdir(parents=True, exist_ok=True)
    return p


def install_desktop(*, open_folder: bool = False) -> dict:
    for d in (AI_ROOT, VIDEOS_FRAME, VIDEOS_MINUTE, ai_root() / "Videos" / "Storyboard"):
        d.mkdir(parents=True, exist_ok=True)

    bats = {
        "Frame starten.bat": "python scripts\\pixverse_studio.py",
        "Dialog GPU Server 24-7.bat": "python scripts\\dialog_studio_server.py --daemon",
        "Dialog GPU Autostart einrichten.bat": "python scripts\\setup_dialog_production.py --skip-server",
        "Dialog Produktion einrichten.bat": "python scripts\\setup_dialog_production.py",
        "Dialog Studio starten.bat": "python scripts\\dialog_studio.py",
        "Dialog Shop LAN starten.bat": "python scripts\\dialog_studio.py --lan",
        "Dialog LAN Firewall.bat": ("python scripts\\dialog_lan_firewall.py", True),
        "VidPuls LAN für alle.bat": ("python scripts\\setup_vidpuls_lan.py", True),
        "GitHub Push.bat": "python scripts\\setup_github_push.py",
        "Jami Dating Video.bat": "python scripts\\build_jami_dating_video.py",
        "Dialog Werbung exportieren.bat": "python scripts\\export_dialog_werbung.py",
        "Storyboard Studio starten.bat": "python scripts\\storyboard_studio.py --lan --no-open",
        "Storyboard Studio LAN.bat": "python scripts\\storyboard_studio.py --lan",
        "Wan2GP Studio starten.bat": "python scripts\\wan2gp_studio.py",
        "Wan2GP einrichten.bat": "python scripts\\setup_wan2gp_amd.py",
        "Wan2GP Pinokio installieren.bat": "python scripts\\install_wan2gp_pinokio.py",
        "Wan2GP starten.bat": "python scripts\\install_wan2gp_pinokio.py --start-only",
        "Wan Prompt exportieren.bat": "python scripts\\export_wan_prompt.py --weekend-date",
        "Wan Video generieren.bat": "python scripts\\run_wan2gp_generate.py",
        "Wan LAN freigeben.bat": "python scripts\\setup_wan2gp_amd.py --firewall-only",
        "Cinema3D einrichten.bat": "python scripts\\setup_3d_video.py",
        "Minute starten.bat": "call start-ia1minute.bat",
        "JamPulse Menü.bat": "call start-jampulse.bat",
        "Autopilot.bat": "python scripts\\auto_passive_earn.py --no-task",
        "AI Autostart einrichten.bat": "python scripts\\jampulse_autostart.py --install --start-now",
    }
    paths: dict[str, str] = {}
    for name, spec in bats.items():
        if isinstance(spec, tuple):
            cmd, admin = spec
            paths[name] = str(_bat(name, cmd, admin=admin))
        else:
            paths[name] = str(_bat(name, spec))

    # Direkt auf dem Desktop (Admin/UAC) – WLAN für alle
    lan_desktop = _bat(
        "VidPuls LAN für alle (Admin).bat",
        "python scripts\\setup_vidpuls_lan.py",
        admin=True,
        dest_dir=DESKTOP,
    )
    paths["desktop_lan_admin"] = str(lan_desktop)

    HTML_DESKTOP.write_text(launcher_html(), encoding="utf-8")

    cfg = {
        "brand": BRAND,
        "desktop_root": str(AI_ROOT),
        "videos_frame": str(VIDEOS_FRAME),
        "videos_minute": str(VIDEOS_MINUTE),
        "html": str(HTML_DESKTOP),
        "starters": paths,
        "repo": str(ROOT),
    }
    (AI_ROOT / "jampulse-ai.json").write_text(
        json.dumps(cfg, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )

    readme = AI_ROOT / "LIES-MICH.txt"
    readme.write_text(
        f"{BRAND} AI – auf dem Desktop\n"
        f"{'=' * 40}\n\n"
        f"Doppelklick:\n"
        f"  Wan2GP Studio starten.bat → lokales KI-Video (Wan/LTX, AMD)\n"
        f"  Wan2GP einrichten.bat → Pinokio-Setup (einmalig)\n"
        f"  Dialog GPU Server 24-7.bat → Kunden-Videos auf deiner GPU (PC 24/7 an)\n"
        f"  Dialog GPU Autostart einrichten.bat → startet Server bei Windows-Login\n"
        f"  Dialog Shop LAN starten.bat → Freunde im WLAN (Shop + Bezahlung)\n"
        f"  VidPuls LAN für alle.bat → Firewall 8793+8795 (Admin)\n"
        f"  Desktop: VidPuls LAN für alle (Admin).bat → gleiches, direkt auf dem Desktop\n"
        f"  Dialog Werbung exportieren.bat → Preise & PayPal für Social Media\n"
        f"  Dialog Studio starten.bat → Dating-Dialog (Sarah & Laura)\n"
        f"  Frame starten.bat  → KI-Video Cloud\n"
        f"  Cinema3D einrichten.bat → 3D-Tools (Rhubarb Lip-Sync)\n"
        f"  Minute starten.bat → 60-Sek.-Video\n"
        f"  JamPulse Menü.bat  → alles\n\n"
        f"Autostart GPU-Shop: Dialog GPU Autostart einrichten.bat\n"
        f"Autostart Frame: AI Autostart einrichten.bat\n\n"
        f"Videos: Videos\\Frame, Videos\\Minute, Wan2GP\\Videos\n\n"
        f"Lokal (0 €): Wan2GP\\ANLEITUNG-WAN2GP.txt\n"
        f"Cloud-Key optional: data\\jami-secrets.local.json\n",
        encoding="utf-8",
    )

    if open_folder:
        try:
            import os

            os.startfile(str(AI_ROOT))  # type: ignore[attr-defined]
        except OSError:
            pass

    return cfg
