#!/bin/bash
# montemusic VLC helper installer — run once per Mac (double-click this file).
# Installs a small local-only server on 127.0.0.1:8766 that lets the
# montemusic.pages.dev VLC button open VLC on THIS Mac. No certificates
# needed: localhost is exempt from browser HTTPS/mixed-content rules.
set -e

INSTALL_DIR="$HOME/.local/share/montemusic-vlc-helper"
mkdir -p "$INSTALL_DIR"

echo "Εγκατάσταση montemusic VLC helper σε $INSTALL_DIR ..."

if ! command -v python3 >/dev/null 2>&1; then
  echo "Δεν βρέθηκε python3. Εγκατέστησε τα Xcode Command Line Tools (xcode-select --install) και ξανατρέξε αυτό το script."
  read -p "Πάτα Enter για κλείσιμο..."
  exit 1
fi

echo "Έλεγχος για yt-dlp..."
python3 -m pip install --user --quiet --upgrade yt-dlp 2>/dev/null || \
  python3 -m pip install --user --quiet --upgrade --break-system-packages yt-dlp

cat > "$INSTALL_DIR/vlc_helper.py" <<'PYEOF'
#!/usr/bin/env python3
"""Local-only VLC helper for montemusic.pages.dev.
Binds to 127.0.0.1 (loopback) with plain HTTP on purpose: localhost is
exempt from browser mixed-content rules, so no certificate is needed —
this only ever serves the browser running on this same Mac.
"""
import json
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

PORT = 8766
ALLOWED_ORIGIN = "https://montemusic.pages.dev"


def resolve_audio_url(youtube_url):
    result = subprocess.run(
        [sys.executable, "-m", "yt_dlp", "--no-playlist", "-f", "bestaudio[ext=m4a]", "-g", youtube_url],
        capture_output=True, text=True, timeout=30,
    )
    if result.returncode != 0:
        raise RuntimeError(result.stderr.strip() or "yt-dlp failed")
    stream_url = result.stdout.strip().splitlines()[0]
    if not stream_url:
        raise RuntimeError("yt-dlp returned no stream URL")
    return stream_url


class Handler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        print("%s - %s" % (self.address_string(), fmt % args))

    def _send_json(self, status, payload):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", ALLOWED_ORIGIN)
        self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "*")
        self.end_headers()

    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)

        if parsed.path == "/vlc":
            youtube_url = params.get("url", [None])[0]
            if not youtube_url:
                return self._send_json(400, {"ok": False, "error": "missing url param"})
            try:
                stream_url = resolve_audio_url(youtube_url)
                subprocess.run(["/usr/bin/open", "-a", "VLC", stream_url], check=True)
                print("Opened in VLC:", youtube_url)
                return self._send_json(200, {"ok": True})
            except Exception as e:
                print("VLC cast failed:", e)
                return self._send_json(500, {"ok": False, "error": str(e)})

        if parsed.path == "/health":
            return self._send_json(200, {"ok": True})

        self._send_json(404, {"ok": False, "error": "not found"})


if __name__ == "__main__":
    server = HTTPServer(("127.0.0.1", PORT), Handler)
    print(f"montemusic VLC helper listening on http://127.0.0.1:{PORT}")
    server.serve_forever()
PYEOF

PLIST="$HOME/Library/LaunchAgents/com.montemusic.vlchelper.plist"
cat > "$PLIST" <<PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.montemusic.vlchelper</string>
    <key>ProgramArguments</key>
    <array>
        <string>$(command -v python3)</string>
        <string>$INSTALL_DIR/vlc_helper.py</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
    <key>StandardOutPath</key>
    <string>$INSTALL_DIR/vlc_helper.log</string>
    <key>StandardErrorPath</key>
    <string>$INSTALL_DIR/vlc_helper.log</string>
</dict>
</plist>
PLISTEOF

launchctl unload "$PLIST" >/dev/null 2>&1 || true
launchctl load -w "$PLIST"

sleep 1
if curl -s -m 3 http://127.0.0.1:8766/health | grep -q '"ok": true'; then
  echo ""
  echo "✅ Έτοιμο! Το κουμπί VLC στο https://montemusic.pages.dev θα δουλεύει τώρα σε αυτό το Mac."
  echo "   (Αν δεν έχεις ήδη VLC εγκατεστημένο: https://www.videolan.org/vlc/)"
else
  echo ""
  echo "⚠️  Κάτι πήγε στραβά. Έλεγξε το log: $INSTALL_DIR/vlc_helper.log"
fi

read -p "Πάτα Enter για κλείσιμο..."
