#!/usr/bin/env python3
"""
Vidseam Companion: a local bridge between the Vidseam extension and yt-dlp.

Listens on 127.0.0.1 only and accepts requests only from the browser extension:
an extension Origin (chrome-extension://...) or, when Chrome omits Origin, the
X-Vidseam-Client header that web pages can't send without a refused preflight.
The extension also blocks sites from reaching this port via declarativeNetRequest.

Run:
    python3 vidseam_companion.py                # port 47811, folder ~/Downloads/Vidseam
    python3 vidseam_companion.py --port 47811 --dir ~/Videos --allow-ext <EXTENSION_ID>

Needs yt-dlp (brew install yt-dlp / pip install yt-dlp) and, ideally, ffmpeg.

Chrome Web Store version: the bridge refuses YouTube links, and yt-dlp's YouTube
extractors are switched off (--use-extractors), so YouTube players embedded
on other pages aren't downloaded either.
"""
from __future__ import annotations

import argparse
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse

VERSION = "1.1.0"
MAX_PARALLEL = 3
PROGRESS_PREFIX = "VIDSEAM_P"
FILE_PREFIX = "VIDSEAM_F"

QUALITY_HEIGHTS = {"2160", "1440", "1080", "720", "480", "360"}
AUDIO_FORMATS = {"mp3", "m4a", "opus", "flac", "wav"}

YOUTUBE_BLOCKED = "YouTube isn't supported in the Chrome version"
YOUTUBE_HOST = re.compile(
    r"(^|\.)(youtube\.com|youtube-nocookie\.com|youtu\.be|youtubekids\.com|googlevideo\.com|ytimg\.com)$",
    re.IGNORECASE,
)
# all YouTube extractors are off, so the generic extractor cannot hand embedded players to them
YTDLP_GUARD = [
    "--use-extractors",
    "default,-.*youtube.*",
    "--match-filters",
    r"extractor_key!~=?(?i)youtube & webpage_url!~=?(?i)(youtube|youtu\.be)",
]


class Blocked(Exception):
    pass


def is_youtube(url: str | None) -> bool:
    if not url:
        return False
    try:
        return bool(YOUTUBE_HOST.search(urlparse(url).hostname or ""))
    except ValueError:
        return False


def assert_allowed(*urls: str | None) -> None:
    if any(is_youtube(u) for u in urls):
        raise Blocked(YOUTUBE_BLOCKED)


def find_ytdlp() -> list[str] | None:
    custom = os.environ.get("VIDSEAM_YTDLP")
    if custom:
        return [custom]
    exe = shutil.which("yt-dlp")
    if exe:
        return [exe]
    try:
        subprocess.run(
            [sys.executable, "-m", "yt_dlp", "--version"],
            capture_output=True,
            check=True,
            timeout=20,
        )
        return [sys.executable, "-m", "yt_dlp"]
    except Exception:
        return None


class Job:
    def __init__(self, url: str, options: dict):
        self.id = uuid.uuid4().hex[:12]
        self.url = url
        self.options = options
        self.title = options.get("title") or url
        self.thumbnail = options.get("thumbnail")
        self.status = "queued"  # queued | downloading | processing | done | error | cancelled
        self.percent = 0.0
        self.speed: float | None = None
        self.eta: int | None = None
        self.downloaded = 0
        self.total: int | None = None
        self.stage = 0
        self.filepath: str | None = None
        self.error: str | None = None
        self.created = time.time()
        self.finished: float | None = None
        self.proc: subprocess.Popen | None = None
        self.log_tail: list[str] = []

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "url": self.url,
            "title": self.title,
            "thumbnail": self.thumbnail,
            "status": self.status,
            "percent": round(self.percent, 1),
            "speed": self.speed,
            "eta": self.eta,
            "downloaded": self.downloaded,
            "total": self.total,
            "stage": self.stage,
            "filepath": self.filepath,
            "filename": Path(self.filepath).name if self.filepath else None,
            "error": self.error,
            "created": self.created,
            "finished": self.finished,
            "quality": self.options.get("quality", "best"),
        }


class Companion:
    def __init__(self, download_dir: Path, allowed_ext: set[str]):
        self.download_dir = download_dir
        self.allowed_ext = allowed_ext
        self.ytdlp = find_ytdlp()
        self.ffmpeg = shutil.which("ffmpeg")
        self.jobs: dict[str, Job] = {}
        self.lock = threading.Lock()
        self.slots = threading.Semaphore(MAX_PARALLEL)
        self._ytdlp_version: str | None = None

    # ---------- info ----------
    def ytdlp_version(self) -> str | None:
        if self._ytdlp_version or not self.ytdlp:
            return self._ytdlp_version
        try:
            out = subprocess.run(
                self.ytdlp + ["--version"], capture_output=True, text=True, timeout=20
            )
            self._ytdlp_version = out.stdout.strip() or None
        except Exception:
            pass
        return self._ytdlp_version

    def health(self) -> dict:
        return {
            "ok": True,
            "name": "vidseam-companion",
            "version": VERSION,
            "ytdlp": self.ytdlp_version(),
            "ffmpeg": bool(self.ffmpeg),
            "downloadDir": str(self.download_dir),
            "platform": platform.system(),
        }

    def probe(self, url: str, referer: str | None, cookies: str | None) -> dict:
        if not self.ytdlp:
            raise RuntimeError("yt-dlp not found. Install it: brew install yt-dlp or pip install yt-dlp")
        assert_allowed(url, referer)
        cmd = self.ytdlp + YTDLP_GUARD + [
            "-J",
            "--flat-playlist",
            "--no-warnings",
            "--playlist-end",
            "200",
        ]
        if referer:
            cmd += ["--referer", referer]
        if cookies:
            cmd += ["--cookies-from-browser", cookies]
        cmd += ["--", url]
        out = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
        if out.returncode != 0:
            raise RuntimeError(clean_error(out.stderr) or "yt-dlp couldn't read this link")
        data = json.loads(out.stdout or "null")
        if not isinstance(data, dict):
            raise RuntimeError("yt-dlp couldn't read this link")
        if "youtube" in str(data.get("extractor_key") or data.get("extractor") or "").lower():
            raise Blocked(YOUTUBE_BLOCKED)
        assert_allowed(data.get("webpage_url"), data.get("url"))
        if data.get("entries"):
            data["entries"] = [e for e in data["entries"] if e and not is_youtube(e.get("url") or e.get("webpage_url"))]
            if not data["entries"]:
                raise Blocked(YOUTUBE_BLOCKED)
        is_playlist = data.get("_type") == "playlist"
        heights = sorted(
            {
                int(f["height"])
                for f in data.get("formats") or []
                if f.get("height") and f.get("vcodec") not in (None, "none")
            },
            reverse=True,
        )
        thumb = data.get("thumbnail")
        if not thumb and data.get("thumbnails"):
            thumb = data["thumbnails"][-1].get("url")
        entries = data.get("entries") or []
        return {
            "title": data.get("title") or data.get("id") or url,
            "uploader": data.get("uploader") or data.get("channel") or data.get("playlist_uploader"),
            "duration": data.get("duration"),
            "thumbnail": thumb,
            "extractor": data.get("extractor_key") or data.get("extractor"),
            "webpageUrl": data.get("webpage_url") or url,
            "isPlaylist": is_playlist,
            "count": len(entries) if is_playlist else 1,
            "heights": heights,
            "isLive": bool(data.get("is_live")),
        }

    # ---------- jobs ----------
    def start(self, url: str, options: dict) -> Job:
        if not self.ytdlp:
            raise RuntimeError("yt-dlp not found. Install it: brew install yt-dlp or pip install yt-dlp")
        assert_allowed(url, options.get("referer"))
        job = Job(url, options)
        with self.lock:
            self.jobs[job.id] = job
        threading.Thread(target=self._run, args=(job,), daemon=True).start()
        return job

    def temp_dir(self, job: Job) -> Path:
        return self.download_dir / ".vidseam-tmp" / job.id

    def build_cmd(self, job: Job) -> list[str]:
        o = job.options
        quality = str(o.get("quality", "best"))
        playlist = bool(o.get("playlist"))
        cmd = self.ytdlp + YTDLP_GUARD + [
            "--newline",
            "--progress",
            "--quiet",
            "--no-warnings",
            "--progress-template",
            f"download:{PROGRESS_PREFIX} %(progress.downloaded_bytes)s|%(progress.total_bytes)s|"
            f"%(progress.total_bytes_estimate)s|%(progress.speed)s|%(progress.eta)s|%(progress.status)s",
            "--print",
            f"after_move:{FILE_PREFIX} %(filepath)s",
            "-P",
            str(self.download_dir),
            # each job gets its own temp folder: parallel downloads
            # of the same video (video + MP3) do not overwrite each other's files
            "-P",
            f"temp:{self.temp_dir(job)}",
        ]
        suffix = f" {quality}p" if quality in QUALITY_HEIGHTS else ""
        if playlist:
            cmd += ["--yes-playlist", "-o", f"%(playlist_title|Playlist)s/%(playlist_index|0)03d - %(title).120B [%(id)s]{suffix}.%(ext)s"]
        else:
            cmd += ["--no-playlist", "-o", f"%(title).150B [%(id)s]{suffix}.%(ext)s"]

        if quality == "audio":
            fmt = o.get("audioFormat", "mp3")
            fmt = fmt if fmt in AUDIO_FORMATS else "mp3"
            cmd += ["-f", "ba/b", "-x", "--audio-format", fmt, "--audio-quality", "0"]
            if self.ffmpeg:
                cmd += ["--embed-thumbnail", "--embed-metadata"]
        else:
            if quality in QUALITY_HEIGHTS:
                h = quality
                cmd += ["-f", f"bv*[height<={h}]+ba/b[height<={h}]/bv*+ba/b"]
            else:
                cmd += ["-f", "bv*+ba/b"]
            if o.get("preferMp4", True):
                cmd += ["-S", "res,vcodec:h264,acodec:m4a", "--merge-output-format", "mp4"]
            if self.ffmpeg and o.get("embedMeta", True):
                cmd += ["--embed-metadata"]
        if o.get("subtitles"):
            cmd += ["--write-subs", "--write-auto-subs", "--sub-langs", o.get("subLangs") or "ru.*,en.*", "--embed-subs"]
        if o.get("referer"):
            cmd += ["--referer", o["referer"]]
        if o.get("cookies"):
            cmd += ["--cookies-from-browser", o["cookies"]]
        cmd += ["--", job.url]
        return cmd

    def _run(self, job: Job) -> None:
        with self.slots:
            if job.status == "cancelled":
                return
            job.status = "downloading"
            try:
                job.proc = subprocess.Popen(
                    self.build_cmd(job),
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    text=True,
                    bufsize=1,
                    encoding="utf-8",
                    errors="replace",
                )
                last_downloaded = -1
                assert job.proc.stdout
                for raw in job.proc.stdout:
                    line = raw.strip()
                    if not line:
                        continue
                    if line.startswith(PROGRESS_PREFIX):
                        last_downloaded = self._parse_progress(job, line, last_downloaded)
                    elif line.startswith(FILE_PREFIX):
                        job.filepath = line[len(FILE_PREFIX):].strip()
                    else:
                        job.log_tail = (job.log_tail + [line])[-12:]
                        if "[Merger]" in line or "[ExtractAudio]" in line or "[Embed" in line:
                            job.status = "processing"
                code = job.proc.wait()
                if job.status == "cancelled":
                    return
                if code == 0:
                    job.status = "done"
                    job.percent = 100.0
                else:
                    job.status = "error"
                    job.error = clean_error("\n".join(job.log_tail)) or f"yt-dlp exited with code {code}"
            except Exception as exc:  # noqa: BLE001
                job.status = "error"
                job.error = str(exc)
            finally:
                job.finished = time.time()
                job.proc = None
                shutil.rmtree(self.temp_dir(job), ignore_errors=True)

    @staticmethod
    def _parse_progress(job: Job, line: str, last_downloaded: int) -> int:
        parts = line[len(PROGRESS_PREFIX):].strip().split("|")
        if len(parts) < 6:
            return last_downloaded

        def num(v: str) -> float | None:
            try:
                return float(v) if v not in ("NA", "None", "") else None
            except ValueError:
                return None

        downloaded = int(num(parts[0]) or 0)
        total = num(parts[1]) or num(parts[2])
        if downloaded < last_downloaded:  # new stream (video → audio)
            job.stage += 1
        job.downloaded = downloaded
        job.total = int(total) if total else None
        job.speed = num(parts[3])
        eta = num(parts[4])
        job.eta = int(eta) if eta is not None else None
        if total:
            job.percent = min(99.9, downloaded / total * 100)
        if job.status == "processing" and parts[5] == "downloading":
            job.status = "downloading"
        return downloaded

    def cancel(self, job_id: str) -> bool:
        job = self.jobs.get(job_id)
        if not job:
            return False
        if job.status in ("queued", "downloading", "processing"):
            job.status = "cancelled"
            job.finished = time.time()
            if job.proc:
                job.proc.terminate()
        return True

    def remove(self, job_id: str) -> bool:
        with self.lock:
            job = self.jobs.get(job_id)
            if not job or job.status in ("queued", "downloading", "processing"):
                return False
            del self.jobs[job_id]
            return True

    def clear_finished(self) -> None:
        with self.lock:
            for jid in [j.id for j in self.jobs.values() if j.status in ("done", "error", "cancelled")]:
                del self.jobs[jid]

    def reveal(self, job_id: str | None) -> None:
        target = self.download_dir
        job = self.jobs.get(job_id) if job_id else None
        if job and job.filepath and Path(job.filepath).exists():
            target = Path(job.filepath)
        system = platform.system()
        if system == "Darwin":
            subprocess.Popen(["open", "-R", str(target)] if target.is_file() else ["open", str(target)])
        elif system == "Windows":
            if target.is_file():
                subprocess.Popen(["explorer", "/select,", str(target)])
            else:
                os.startfile(str(target))  # type: ignore[attr-defined]
        else:
            subprocess.Popen(["xdg-open", str(target.parent if target.is_file() else target)])


def clean_error(text: str) -> str:
    lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
    errors = [ln for ln in lines if ln.startswith("ERROR")]
    msg = (errors[-1] if errors else (lines[-1] if lines else "")).replace("ERROR: ", "")
    return msg[:400]


def make_handler(app: Companion):
    class Handler(BaseHTTPRequestHandler):
        server_version = f"VidseamCompanion/{VERSION}"

        def log_message(self, fmt, *args):  # quiet
            pass

        # ----- security -----
        def _origin_ok(self) -> bool:
            origin = self.headers.get("Origin", "")
            if origin:
                if not origin.startswith(("chrome-extension://", "moz-extension://")):
                    return False
                if app.allowed_ext:
                    return origin.split("://", 1)[1].rstrip("/") in app.allowed_ext
                return True
            # Chrome sends no Origin for requests from an extension that has host
            # permissions. The extension adds this header instead: a web page can't
            # send a custom header without a CORS preflight, and preflights from
            # web origins are refused above.
            return self.headers.get("X-Vidseam-Client") == "extension"

        def _cors(self):
            origin = self.headers.get("Origin", "")
            if origin and self._origin_ok():
                self.send_header("Access-Control-Allow-Origin", origin)
                self.send_header("Vary", "Origin")
                self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
                self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Vidseam-Client")
                self.send_header("Access-Control-Allow-Private-Network", "true")

        def _json(self, code: int, payload) -> None:
            body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
            self.send_response(code)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store")
            self._cors()
            self.end_headers()
            self.wfile.write(body)

        def _body(self) -> dict:
            length = int(self.headers.get("Content-Length") or 0)
            if length <= 0 or length > 64_000:
                return {}
            try:
                return json.loads(self.rfile.read(length).decode("utf-8"))
            except Exception:
                return {}

        def _guard(self) -> bool:
            if not self._origin_ok():
                self._json(403, {"error": "forbidden: only the Vidseam extension may call this server"})
                return False
            return True

        # ----- methods -----
        def do_OPTIONS(self):
            self.send_response(204 if self._origin_ok() else 403)
            self._cors()
            self.end_headers()

        def do_GET(self):
            if not self._guard():
                return
            u = urlparse(self.path)
            q = parse_qs(u.query)
            try:
                if u.path == "/health":
                    return self._json(200, app.health())
                if u.path == "/info":
                    url = (q.get("url") or [""])[0]
                    if not url.startswith(("http://", "https://")):
                        return self._json(400, {"error": "An http(s) link is required"})
                    info = app.probe(url, (q.get("referer") or [None])[0], (q.get("cookies") or [None])[0])
                    return self._json(200, info)
                if u.path == "/jobs":
                    jobs = sorted(app.jobs.values(), key=lambda j: j.created, reverse=True)
                    return self._json(200, {"jobs": [j.to_dict() for j in jobs]})
                return self._json(404, {"error": "not found"})
            except Blocked as exc:
                return self._json(403, {"error": str(exc)})
            except subprocess.TimeoutExpired:
                return self._json(504, {"error": "yt-dlp didn't respond in time"})
            except Exception as exc:  # noqa: BLE001
                return self._json(500, {"error": str(exc)})

        def do_POST(self):
            if not self._guard():
                return
            u = urlparse(self.path)
            body = self._body()
            try:
                if u.path == "/download":
                    url = str(body.get("url") or "")
                    if not url.startswith(("http://", "https://")):
                        return self._json(400, {"error": "An http(s) link is required"})
                    job = app.start(url, body)
                    return self._json(200, job.to_dict())
                parts = u.path.strip("/").split("/")
                if len(parts) == 3 and parts[0] == "jobs" and parts[2] == "cancel":
                    return self._json(200 if app.cancel(parts[1]) else 404, {"ok": True})
                if u.path == "/jobs/clear":
                    app.clear_finished()
                    return self._json(200, {"ok": True})
                if u.path == "/reveal":
                    app.reveal(body.get("id"))
                    return self._json(200, {"ok": True})
                return self._json(404, {"error": "not found"})
            except Blocked as exc:
                return self._json(403, {"error": str(exc)})
            except Exception as exc:  # noqa: BLE001
                return self._json(500, {"error": str(exc)})

        def do_DELETE(self):
            if not self._guard():
                return
            parts = urlparse(self.path).path.strip("/").split("/")
            if len(parts) == 2 and parts[0] == "jobs":
                return self._json(200 if app.remove(parts[1]) else 409, {"ok": True})
            return self._json(404, {"error": "not found"})

    return Handler


def main() -> None:
    p = argparse.ArgumentParser(description="Vidseam Companion: bridge from the Vidseam extension to yt-dlp")
    p.add_argument("--port", type=int, default=int(os.environ.get("VIDSEAM_PORT", 47811)))
    p.add_argument("--dir", default=os.environ.get("VIDSEAM_DIR", str(Path.home() / "Downloads" / "Vidseam")))
    p.add_argument("--allow-ext", action="append", default=[], help="Allow only this extension ID (can be repeated)")
    args = p.parse_args()

    download_dir = Path(args.dir).expanduser().resolve()
    download_dir.mkdir(parents=True, exist_ok=True)
    app = Companion(download_dir, set(args.allow_ext))

    server = ThreadingHTTPServer(("127.0.0.1", args.port), make_handler(app))
    print(f"◆ Vidseam Companion {VERSION}")
    print(f"  listening    http://127.0.0.1:{args.port}")
    print(f"  yt-dlp       {app.ytdlp_version() or 'NOT FOUND: brew install yt-dlp'}")
    print(f"  ffmpeg       {'found' if app.ffmpeg else 'missing (1080p+ merging and MP3 will be unavailable)'}")
    print(f"  saving to    {download_dir}")
    print("  Ctrl+C to stop")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nstopped")


if __name__ == "__main__":
    main()
