import json
from pathlib import Path

from flashdata import FlashData

video_id = "jNQXAC9IVRw"
checkpoint = Path(f"flashdata-{video_id}.job")

with FlashData(api_key="your-flashdata-api-key") as client:
    if not checkpoint.exists():
        # Reserve the file first: an uncertain submission must not be repeated.
        with checkpoint.open("x", encoding="utf-8") as saved:
            job = client.youtube.download(
                video_id,
                download_type="audio_video",
                output_format="mp4",
                video_quality="<=1080",
                upload_metadata=True,
                storage={
                    "storage_type": "s3",
                    "storage_url": "your-media-bucket",
                    "region": "us-east-1",
                    "access_key": "your-storage-access-key",
                    "secret_key": "your-storage-secret-key",
                },
            )
            saved.write(job["id"])

    job_id = checkpoint.read_text(encoding="utf-8").strip()
    if not job_id:
        raise RuntimeError("Submission outcome unknown; check console job history")

    print("Job ID:", job_id)
    # Rerunning waits for this saved job, without submitting another download.
    client.jobs.wait(job_id, timeout=900)
    result = client.jobs.result(job_id)
    manifest = Path(f"flashdata-{video_id}.json")
    manifest.write_text(json.dumps(result, indent=2), encoding="utf-8")
    print(json.dumps(result, indent=2))
