#!/usr/bin/env python3
"""
yt_upload.py — Download a YouTube track and add it to your music collection.

Requirements:
    pip install yt-dlp requests

Usage:
    export SITE_PASS=yourpassword          # once in your shell profile
    python yt_upload.py "https://youtube.com/watch?v=..."

Options:
    --title    TITLE       Override title (auto-fetched)
    --artist   ARTIST      Override artist / creator
    --year     YEAR
    --note     NOTE        Personal note
    --category CATEGORY    (default: Listening)
    --browser  BROWSER     Browser to read cookies from (default: chrome)
                           Options: chrome, firefox, safari, brave, edge
"""

import argparse
import os
import sys
import tempfile
import requests

try:
    import yt_dlp
except ImportError:
    sys.exit("yt-dlp not found. Run: pip install yt-dlp")

API = "https://linlifeng-site.linlifeng.workers.dev"


def login(session, password):
    r = session.post(f"{API}/api/auth/login", json={"password": password})
    r.raise_for_status()
    if not r.json().get("ok"):
        sys.exit(f"Login failed: {r.json()}")


def download_audio(url, output_dir, browser):
    ydl_opts = {
        "format": "bestaudio[ext=m4a]/bestaudio[ext=webm]/bestaudio/best",
        "outtmpl": os.path.join(output_dir, "%(id)s.%(ext)s"),
        "cookiesfrombrowser": (browser,),  # reads live session — no cookie export needed
        "quiet": False,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=True)

    ext = info.get("ext", "m4a")
    filepath = os.path.join(output_dir, f"{info['id']}.{ext}")
    if not os.path.exists(filepath):
        files = [f for f in os.listdir(output_dir) if not f.endswith(".part")]
        if not files:
            sys.exit("Download produced no output file")
        filepath = os.path.join(output_dir, files[0])
        ext = filepath.rsplit(".", 1)[-1]

    mime = "audio/mp4" if ext in ("m4a", "mp4") else f"audio/{ext}"
    title = info.get("title", "Unknown")
    artist = info.get("uploader") or info.get("channel") or ""
    return filepath, mime, title, artist


def upload(session, filepath, mime, title, creator, year, note, category):
    with open(filepath, "rb") as f:
        r = session.post(
            f"{API}/api/chapters/music/works",
            files={"file": (os.path.basename(filepath), f, mime)},
            data={k: v for k, v in {
                "title": title, "creator": creator, "year": year,
                "description": note, "category": category,
            }.items() if v},
        )
    r.raise_for_status()
    result = r.json()
    if result.get("ok"):
        print(f"Saved: {title}  (id={result['id']})")
    else:
        sys.exit(f"Upload failed: {result}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="YouTube URL")
    parser.add_argument("--password", default=os.environ.get("SITE_PASS"))
    parser.add_argument("--title")
    parser.add_argument("--artist")
    parser.add_argument("--year")
    parser.add_argument("--note")
    parser.add_argument("--category", default="Listening")
    parser.add_argument("--browser", default="chrome")
    args = parser.parse_args()

    if not args.password:
        sys.exit("Set SITE_PASS env var or pass --password")

    session = requests.Session()
    login(session, args.password)

    with tempfile.TemporaryDirectory() as tmpdir:
        filepath, mime, auto_title, auto_artist = download_audio(args.url, tmpdir, args.browser)
        title = args.title or auto_title
        artist = args.artist or auto_artist
        print(f"Uploading: {title} — {artist}")
        upload(session, filepath, mime, title, artist, args.year, args.note, args.category)


if __name__ == "__main__":
    main()
