"""IIDX local yt-dlp bridge. Run with Python 3.10+; no web server or Docker needed.

The browser connects directly to loopback after the user enters the connection
code printed at startup. Only YouTube video IDs are accepted, never shell args.
"""
import argparse
import concurrent.futures
import hmac
import importlib.util
import json
import logging
import math
import os
from pathlib import Path
import re
import secrets
import shutil
import signal
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit

VIDEO_ID = re.compile(r"[A-Za-z0-9_-]{11}\Z")
MAX_BYTES = 40 * 1024 * 1024
MAX_SECONDS = 360
DEFAULT_ORIGINS = {"https://iidx-play.cee.ee",
                   "https://iidx-combo-practice.cee-cirno-6905.chatgpt.site"}


def downloader_command():
    executable = shutil.which("yt-dlp")
    if executable:
        return [executable]
    if importlib.util.find_spec("yt_dlp"):
        return [sys.executable, "-m", "yt_dlp"]
    return None


def dependency_status():
    return {"yt-dlp": bool(downloader_command()), "ffmpeg": bool(shutil.which("ffmpeg")),
            "ffprobe": bool(shutil.which("ffprobe")),
            "JavaScript runtime (Deno / Node)": bool(shutil.which("deno") or shutil.which("node"))}


def run_process(arguments, timeout, cwd):
    # A process group also contains FFmpeg; a timed-out download leaves no child.
    with tempfile.TemporaryFile() as output:
        process = subprocess.Popen(arguments, cwd=cwd, stdout=output,
                                   stderr=subprocess.STDOUT, start_new_session=True)
        try:
            process.wait(timeout=timeout)
        except subprocess.TimeoutExpired:
            if os.name == "nt":
                subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
                if process.poll() is None:
                    process.kill()
            else:
                os.killpg(process.pid, signal.SIGKILL)
            process.wait()
            raise ValueError("下载超时，请稍后重试。") from None
        output.seek(max(0, output.tell() - 4096))
        result = output.read().decode("utf-8", "replace")
        if process.returncode:
            # Do not expose upstream URLs, tokens, or the server filesystem.
            logging.warning("Audio subprocess failed: %s (exit %s)", arguments[0], process.returncode)
            raise ValueError("音频读取失败；视频可能不可用、需要登录或被来源服务限制。")
        return result


def download_audio(video_id, destination):
    dependencies = dependency_status()
    missing = [name for name, present in dependencies.items() if not present]
    if missing:
        raise ValueError("请先安装：" + "、".join(missing))
    with tempfile.TemporaryDirectory(prefix="download-", dir=destination.parent) as directory:
        command = downloader_command() + ["--ignore-config", "--no-plugin-dirs",
                   "--no-remote-components", "--no-playlist", "--no-progress", "--no-warnings",
                   "--no-cache-dir", "--js-runtimes", "deno" if shutil.which("deno") else "node", "--socket-timeout", "20",
                   "--retries", "1", "--fragment-retries", "1", "--extractor-retries", "1",
                   "--abort-on-unavailable-fragments", "--max-filesize", str(MAX_BYTES),
                   "--match-filters", f"!is_live & duration <= {MAX_SECONDS}",
                   "-f", "bestaudio[ext=m4a]/bestaudio", "--extract-audio",
                   "--audio-format", "m4a", "--audio-quality", "160K",
                   "-o", "audio.%(ext)s", "--", "https://www.youtube.com/watch?v=" + video_id]
        run_process(command, 180, directory)
        audio = Path(directory) / "audio.m4a"
        if not audio.is_file() or not 0 < audio.stat().st_size <= MAX_BYTES:
            raise ValueError("没有生成有效音频，或文件超过 40 MB / 6 分钟限制。")
        duration = float(run_process(["ffprobe", "-v", "error", "-show_entries", "format=duration",
                                      "-of", "default=noprint_wrappers=1:nokey=1", str(audio)], 15, directory).strip())
        if not math.isfinite(duration) or not 0 < duration <= MAX_SECONDS + 1:
            raise ValueError("音频时长需在 6 分钟以内。")
        os.replace(audio, destination)
        return duration


class AudioCache:
    def __init__(self, directory, quota=1024 * 1024 * 1024, downloader=download_audio):
        self.directory = Path(directory)
        self.directory.mkdir(parents=True, exist_ok=True)
        self.quota, self.downloader = quota, downloader
        self.lock = threading.RLock()
        self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
        with self.connect() as db:
            db.execute("CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, state TEXT NOT NULL, error TEXT NOT NULL DEFAULT '', duration REAL, updated REAL NOT NULL)")
            db.execute("UPDATE jobs SET state='error',error='服务重启中断了下载，请重试。' WHERE state IN ('queued','running')")
        for path in self.directory.glob("download-*"):
            if path.is_dir():
                shutil.rmtree(path)

    def connect(self):
        db = sqlite3.connect(self.directory / "jobs.sqlite", timeout=15)
        db.row_factory = sqlite3.Row
        return db

    def path(self, video_id):
        if not isinstance(video_id, str) or not VIDEO_ID.fullmatch(video_id):
            raise ValueError("视频编号无效。")
        return self.directory / (video_id + ".m4a")

    def status(self, video_id):
        path = self.path(video_id)
        with self.lock, self.connect() as db:
            row = db.execute("SELECT * FROM jobs WHERE id=?", (video_id,)).fetchone()
            result = dict(row) if row else {"id": video_id, "state": "missing"}
            if result["state"] == "ready":
                if path.is_file():
                    result["bytes"] = path.stat().st_size
                else:
                    result.update(state="missing", error="缓存文件已移除，请重新下载。")
            return result

    def enqueue(self, video_id):
        with self.lock, self.connect() as db:
            state = self.status(video_id)
            if state["state"] in ("queued", "running", "ready"):
                return state
            pending = db.execute("SELECT count(*) FROM jobs WHERE state IN ('queued','running')").fetchone()[0]
            if pending >= 8:
                raise OverflowError("下载队列已满，请稍后重试。")
            db.execute("INSERT INTO jobs(id,state,updated) VALUES(?,'queued',?) ON CONFLICT(id) DO UPDATE SET state='queued',error='',duration=NULL,updated=excluded.updated", (video_id, time.time()))
        self.pool.submit(self.work, video_id)
        return {"id": video_id, "state": "queued"}

    def work(self, video_id):
        path = self.path(video_id)
        try:
            with self.lock, self.connect() as db:
                db.execute("UPDATE jobs SET state='running',updated=? WHERE id=?", (time.time(), video_id))
            # Reserve temporary + final space. No silent removal of retained songs.
            used = sum(p.stat().st_size for p in self.directory.glob("*.m4a"))
            if used + 3 * MAX_BYTES > self.quota or shutil.disk_usage(self.directory).free < 3 * MAX_BYTES:
                raise ValueError("本机音频空间不足，请清理缓存目录或调整空间上限。")
            duration = self.downloader(video_id, path)
            with self.connect() as db:
                db.execute("UPDATE jobs SET state='ready',error='',duration=?,updated=? WHERE id=?", (duration, time.time(), video_id))
        except Exception as error:
            path.unlink(missing_ok=True)
            message = str(error) if isinstance(error, ValueError) else "本机下载失败，请检查 yt-dlp 后重试。"
            with self.connect() as db:
                db.execute("UPDATE jobs SET state='error',error=?,updated=? WHERE id=?", (message[:250], time.time(), video_id))


def byte_range(value, length):
    if not value:
        return 0, length - 1, False
    match = re.fullmatch(r"bytes=(\d*)-(\d*)", value)
    if not match or not any(match.groups()):
        raise ValueError("Invalid range")
    first, last = match.groups()
    if first:
        start, end = int(first), min(int(last), length - 1) if last else length - 1
    else:
        start, end = max(0, length - int(last)), length - 1
    if start > end or start >= length:
        raise ValueError("Invalid range")
    return start, end, True


class Handler(BaseHTTPRequestHandler):
    server_version = "IIDXLocalAudio/1"

    def setup(self):
        super().setup()
        self.connection.settimeout(20)

    def log_message(self, *args):
        pass  # Never log authorization or query parameters.

    def end_headers(self):
        origin = self.headers.get("Origin")
        if origin in self.server.allowed_origins:
            self.send_header("Access-Control-Allow-Origin", origin)
            self.send_header("Vary", "Origin")
            self.send_header("Access-Control-Expose-Headers", "Content-Length, Content-Range")
        self.send_header("X-Content-Type-Options", "nosniff")
        super().end_headers()

    def allowed_request(self):
        # Check Host as well as Origin to reject DNS rebinding and opaque origins.
        if self.headers.get("Host", "").lower() not in self.server.allowed_hosts:
            self.send_json({"error": "Local host required"}, 403)
            return False
        origin = self.headers.get("Origin")
        if origin is not None and origin not in self.server.allowed_origins:
            self.send_json({"error": "Origin not allowed"}, 403)
            return False
        return True

    def do_OPTIONS(self):
        if not self.allowed_request():
            return
        requested = {h.strip().lower() for h in self.headers.get("Access-Control-Request-Headers", "").split(",") if h.strip()}
        if (self.headers.get("Origin") not in self.server.allowed_origins
                or self.headers.get("Access-Control-Request-Method") not in {"GET", "HEAD", "POST"}
                or not requested <= {"authorization", "content-type", "range"}):
            return self.send_json({"error": "Preflight rejected"}, 403)
        self.send_response(204)
        self.send_header("Access-Control-Allow-Methods", "GET, HEAD, POST")
        self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
        self.send_header("Access-Control-Max-Age", "600")
        if self.headers.get("Access-Control-Request-Private-Network") == "true":
            self.send_header("Access-Control-Allow-Private-Network", "true")
        self.send_header("Content-Length", "0")
        self.end_headers()

    def send_json(self, data, status=200):
        body = json.dumps(data, ensure_ascii=False).encode()
        self.send_response(status)
        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.end_headers()
        if self.command != "HEAD":
            self.wfile.write(body)

    def route(self):
        if not self.allowed_request():
            return
        path = urlsplit(self.path).path
        if not hmac.compare_digest(self.headers.get("Authorization", "").encode(), ("Bearer " + self.server.token).encode()):
            return self.send_json({"error": "连接码不正确，请复制终端里显示的连接码。"}, 401)
        if path == "/health" and self.command == "GET":
            return self.send_json({"ok": True, "service": "iidx-local-audio", "version": 1,
                                   "dependencies": dependency_status()})
        cache = self.server.cache
        try:
            if path == "/v1/jobs" and self.command == "POST":
                if self.headers.get("Transfer-Encoding") or self.headers.get_content_type() != "application/json":
                    return self.send_json({"error": "Invalid content type"}, 415)
                length = int(self.headers.get("Content-Length", "0"))
                if not 0 < length <= 1024:
                    return self.send_json({"error": "Invalid request size"}, 413)
                data = json.loads(self.rfile.read(length))
                if not isinstance(data, dict) or set(data) != {"video_id"}:
                    raise ValueError("只接受单个 YouTube 视频编号。")
                return self.send_json(cache.enqueue(data["video_id"]), 202)
            match = re.fullmatch(r"/v1/(jobs|audio)/([A-Za-z0-9_-]{11})", path)
            if not match or self.command not in ("GET", "HEAD"):
                return self.send_json({"error": "Not found"}, 404)
            kind, video_id = match.groups()
            state = cache.status(video_id)
            if kind == "jobs":
                return self.send_json(state)
            if state["state"] != "ready":
                return self.send_json({"error": "音频尚未缓存。"}, 404)
            length = state["bytes"]
            try:
                start, end, partial = byte_range(self.headers.get("Range"), length)
            except ValueError:
                self.send_response(416)
                self.send_header("Content-Range", f"bytes */{length}")
                self.end_headers()
                return
            self.send_response(206 if partial else 200)
            self.send_header("Content-Type", "audio/mp4")
            self.send_header("Content-Length", str(end - start + 1))
            self.send_header("Accept-Ranges", "bytes")
            self.send_header("Cache-Control", "private, no-store")
            if partial:
                self.send_header("Content-Range", f"bytes {start}-{end}/{length}")
            self.end_headers()
            if self.command == "HEAD":
                return
            with cache.path(video_id).open("rb") as audio:
                audio.seek(start)
                remaining = end - start + 1
                while remaining:
                    chunk = audio.read(min(65536, remaining))
                    if not chunk:
                        break
                    self.wfile.write(chunk)
                    remaining -= len(chunk)
        except OverflowError as error:
            self.send_json({"error": str(error)}, 429)
        except (ValueError, TypeError):
            self.send_json({"error": "请求或视频编号无效。"}, 400)
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            pass
        except Exception:
            logging.exception("Audio request failed")
            self.send_json({"error": "服务暂时不可用。"}, 503)

    do_GET = do_HEAD = do_POST = route


def make_server(address, cache, token, allowed_origins=None):
    if len(token) < 32 or not token.isascii():
        raise ValueError("AUDIO_SERVICE_TOKEN must contain at least 32 ASCII characters")
    server = ThreadingHTTPServer(address, Handler)
    server.cache, server.token = cache, token
    server.allowed_origins = set(DEFAULT_ORIGINS if allowed_origins is None else allowed_origins)
    server.allowed_hosts = {f"127.0.0.1:{server.server_port}", f"localhost:{server.server_port}"}
    return server


def main():
    parser = argparse.ArgumentParser(description="IIDX 本机 yt-dlp 连接程序（无需 Docker）")
    parser.add_argument("--port", type=int, default=18765)
    parser.add_argument("--data-dir", type=Path, default=Path.home() / ".iidx-audio")
    parser.add_argument("--quota-mb", type=int, default=1024)
    parser.add_argument("--allow-origin", action="append", default=[], help="额外允许的网页来源（完整 HTTPS origin）")
    args = parser.parse_args()
    if not 1024 <= args.port <= 65535 or args.quota_mb < 120:
        parser.error("端口需为 1024–65535，缓存上限至少 120 MB")
    origins = set(DEFAULT_ORIGINS)
    for origin in args.allow_origin:
        url = urlsplit(origin)
        if url.scheme != "https" or not url.hostname or url.username or url.password or url.path or url.query or url.fragment:
            parser.error("--allow-origin 只接受完整 HTTPS origin，不包含路径")
        origins.add(origin)
    # A fresh code per launch; cached audio survives restarts, credentials do not.
    token = secrets.token_urlsafe(32)
    audio_cache = AudioCache(args.data_dir, args.quota_mb * 1024 * 1024)
    try:
        server = make_server(("127.0.0.1", args.port), audio_cache, token, origins)
    except OSError as error:
        audio_cache.pool.shutdown(wait=False)
        parser.exit(1, f"无法启动连接程序：{error}。可使用 --port 更换端口。\n")
    print(f"\nIIDX 本机音频已启动\n地址：http://127.0.0.1:{args.port}\n连接码：{token}\n音频目录：{args.data_dir.resolve()}\n", flush=True)
    missing = [name for name, present in dependency_status().items() if not present]
    if missing:
        print("尚需安装：" + "、".join(missing), flush=True)
    print("在网页「后台 / 离线音频 → 连接本机 yt-dlp」填写地址和连接码。保持此窗口开启；Ctrl+C 退出。", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()
        audio_cache.pool.shutdown(wait=True, cancel_futures=True)


if __name__ == "__main__":
    main()
