"""Ingest a manually-produced shot into the Recoil manifest.

Usage:
    python3 -m recoil.pipeline.tools.ingest_cli \
        --url https://media.flora.ai/.../video.mp4 \
        --shot-id EP001_SH05A \
        --parent-take EP001_SH05A_T2 \
        --project tartarus \
        --episode 1
"""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

import requests

from recoil.core.paths import projects_root


def _download(url: str, dest: Path) -> bool:
    try:
        resp = requests.get(url, stream=True, timeout=120)
        resp.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in resp.iter_content(chunk_size=8192):
                f.write(chunk)
        return True
    except Exception as e:
        print(f"[ingest] download failed: {e}", file=sys.stderr)
        return False


def _hash_file(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()[:16]


def ingest(
    url: str,
    shot_id: str,
    parent_take: str,
    project: str,
    episode: int,
    reason: str = "manual iteration in Flora UI",
) -> dict:
    """Download and ingest a manual shot into the project output directory."""
    output_dir = projects_root() / project / "output" / "video"
    output_dir.mkdir(parents=True, exist_ok=True)

    ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
    filename = f"{shot_id}_manual_{ts}.mp4"
    dest = output_dir / filename

    if not _download(url, dest):
        return {"success": False, "error": "download failed"}

    file_hash = _hash_file(dest)
    take_id = f"{shot_id}_M{ts[-6:]}"

    record = {
        "take_id": take_id,
        "shot_id": shot_id,
        "episode_id": f"{project}_s01e{episode:02d}",
        "project": project,
        "provenance": "manual",
        "parent_take": parent_take,
        "source_url": url,
        "local_path": str(dest),
        "file_hash": file_hash,
        "ingested_at": datetime.now(timezone.utc).isoformat(),
        "change_reason": reason,
    }

    manifest_dir = projects_root() / project / "output" / "manifests"
    manifest_dir.mkdir(parents=True, exist_ok=True)
    ingest_log = manifest_dir / "manual_ingests.jsonl"
    with open(ingest_log, "a") as f:
        f.write(json.dumps(record) + "\n")

    return {"success": True, **record}


def main():
    parser = argparse.ArgumentParser(description="Ingest a manual shot into Recoil manifest")
    parser.add_argument("--url", required=True, help="URL of the video to ingest")
    parser.add_argument("--shot-id", required=True, help="Shot ID (e.g., EP001_SH05A)")
    parser.add_argument("--parent-take", required=True, help="Parent take ID this was iterated from")
    parser.add_argument("--project", required=True, help="Project name (e.g., tartarus)")
    parser.add_argument("--episode", type=int, required=True, help="Episode number")
    parser.add_argument("--reason", default="manual iteration in Flora UI")
    args = parser.parse_args()

    result = ingest(
        url=args.url,
        shot_id=args.shot_id,
        parent_take=args.parent_take,
        project=args.project,
        episode=args.episode,
        reason=args.reason,
    )
    print(json.dumps(result, indent=2))
    sys.exit(0 if result["success"] else 1)


if __name__ == "__main__":
    main()
