import json
from pathlib import Path

from flashdata import FlashData


def save_json(path, value):
    path.write_text(json.dumps(value, indent=2), encoding="utf-8")


def collect_dataset_item(client, video_id, storage, directory="dataset"):
    folder = Path(directory) / video_id
    folder.mkdir(parents=True, exist_ok=True)
    receipt = folder / "download-job-id.txt"

    if not receipt.exists():
        # Reserve the checkpoint before submitting; never overwrite an old ID.
        with receipt.open("x", encoding="utf-8") as checkpoint:
            job = client.youtube.download(
                video_id,
                storage=storage,
                download_type="audio_video",
                output_format="mp4",
                yt_dlp_format="bestvideo+bestaudio/best",
                upload_metadata=True,
            )
            checkpoint.write(job["id"])

    job_id = receipt.read_text(encoding="utf-8").strip()
    if not job_id:
        raise RuntimeError("Submission outcome unknown; inspect job history first")

    # A rerun waits for the saved job instead of downloading the video again.
    client.jobs.wait(job_id, timeout=900)
    delivery = client.jobs.result(job_id)
    save_json(folder / "delivery.json", delivery)

    # Captions are a separate YouTube Data request, with their own usage charge.
    response = client.youtube.captions(video_id, language=["en"], auto=True)
    captions = response["results"][0]
    save_json(folder / "captions.json", captions)

    item = {
        "video_id": video_id,
        "download_job_id": job_id,
        "media": delivery["results"][0],
        "captions_file": "captions.json",
        "caption_status": "available" if captions["tracks"] else "needs_review",
    }
    save_json(folder / "item.json", item)
    return item


if __name__ == "__main__":
    storage = {
        "storage_type": "s3",
        "storage_url": "your-media-bucket",
        "object_prefix": "datasets/ytdlp-migration/run-01",
        "region": "us-east-1",
        "access_key": "your-storage-access-key",
        "secret_key": "your-storage-secret-key",
    }
    with FlashData(api_key="your-flashdata-api-key") as client:
        item = collect_dataset_item(client, "jNQXAC9IVRw", storage)
    print(json.dumps(item, indent=2))
