"""Download an allowed YouTube source through Agent Reach's yt-dlp backend and render one Short."""
import argparse
import json
import os
import subprocess
from pathlib import Path

ROOT = Path(__file__).parent
SOURCE_DIR = ROOT / "footage" / "sources"
YTDLP = Path(os.environ.get("AGENT_REACH_YTDLP", "/root/.agent-reach-venv/bin/yt-dlp"))
DEFAULT_COOKIES = Path("/root/workspace/shorts_data/youtube-cookies.txt")


def download_source(url: str, video_id: str, cookies: Path) -> tuple[Path, dict]:
    SOURCE_DIR.mkdir(parents=True, exist_ok=True)
    output = SOURCE_DIR / f"{video_id}.mp4"
    metadata_path = SOURCE_DIR / f"{video_id}.info.json"
    if not output.exists() or not metadata_path.exists():
        if not YTDLP.exists():
            raise FileNotFoundError(f"Agent Reach yt-dlp backend not found: {YTDLP}")
        if not cookies.exists():
            raise FileNotFoundError(f"YouTube cookies file not found: {cookies}")
        cmd = [
            str(YTDLP), "--cookies", str(cookies), "--no-playlist",
            "--merge-output-format", "mp4",
            "-f", "bv*[height>=1440]+ba/bv*+ba",
            "--write-info-json", "-o", str(SOURCE_DIR / f"{video_id}.%(ext)s"), url,
        ]
        subprocess.run(cmd, check=True)
    metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
    license_name = (metadata.get("license") or "").lower()
    if "creative commons" not in license_name:
        raise RuntimeError(f"Source license is not Creative Commons: {metadata.get('license')!r}")
    if not output.exists():
        raise FileNotFoundError(f"Downloaded source missing: {output}")
    return output, metadata


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", default="https://www.youtube.com/watch?v=LwqyaFWDey8")
    parser.add_argument("--video-id", default="LwqyaFWDey8")
    parser.add_argument("--cookies", type=Path, default=Path(os.environ.get("YOUTUBE_COOKIES_FILE", DEFAULT_COOKIES)))
    parser.add_argument("--offset", type=float, default=300.0)
    parser.add_argument("--stem", default="the_lookout_note")
    args = parser.parse_args()

    source, metadata = download_source(args.url, args.video_id, args.cookies)
    subprocess.run([
        str(ROOT / "venv" / "bin" / "python3"), "create_final_clip.py",
        "--footage", str(source), "--offset", str(args.offset), "--stem", args.stem,
    ], cwd=ROOT, check=True)
    print(json.dumps({
        "source": str(source),
        "title": metadata.get("title"),
        "uploader": metadata.get("uploader"),
        "license": metadata.get("license"),
        "credit": metadata.get("uploader"),
        "published": False,
    }, indent=2))


if __name__ == "__main__":
    main()