#!/usr/bin/env python3
"""TakeAI public API: upload a recording, wait for the edit, download it.

Set TAKEAI_API_KEY in your environment/secret manager first. No dependencies.
Usage: python3 api-example.py input.mp4 --output edited.mp4
"""
import argparse
import json
import os
from pathlib import Path
import sys
import time
import urllib.error
import urllib.request

BASE = "https://usetake.ai/api/v1"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("video", type=Path)
    parser.add_argument("--output", type=Path, default=Path("edited.mp4"))
    parser.add_argument("--intent", default="Tighten the pauses and add captions")
    parser.add_argument("--timeout", type=int, default=1800)
    args = parser.parse_args()
    key = os.environ.get("TAKEAI_API_KEY", "").strip()
    if not key:
        parser.error("Set TAKEAI_API_KEY to a personal key from TakeAI Account settings.")
    if not args.video.is_file() or args.video.stat().st_size == 0:
        parser.error("Choose a non-empty video file.")
    if args.output.exists():
        parser.error("The output already exists. Choose another --output path.")

    def request(method, path, data=None):
        headers = {"Authorization": f"Bearer {key}", "X-TakeAI-Client": "api"}
        if isinstance(data, dict):
            data = json.dumps(data).encode()
            headers["Content-Type"] = "application/json"
        elif isinstance(data, bytes):
            headers["Content-Type"] = "application/octet-stream"
        req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
        # Chunks and completing the same upload are safe to repeat. Other
        # mutations are not automatically replayed after a lost response.
        retryable = method == "GET" or method == "PUT" or path.endswith("/complete")
        for attempt in range(6):
            try:
                return urllib.request.urlopen(req, timeout=90)
            except urllib.error.HTTPError as error:
                if retryable and error.code in (429, 502, 503, 504) and attempt < 5:
                    delay = error.headers.get("Retry-After", "")
                    time.sleep(min(120, int(delay)) if delay.isdigit() else min(30, 2 ** attempt))
                    error.close()
                    continue
                detail = error.read().decode(errors="replace")
                raise RuntimeError(f"API returned {error.code}: {detail}") from None
            except urllib.error.URLError:
                if not retryable or attempt == 5:
                    raise RuntimeError("Connection interrupted. Check the video/upload state before starting another upload.") from None
                time.sleep(min(30, 2 ** attempt))

    def api(method, path, data=None):
        with request(method, path, data) as response:
            return json.load(response)

    upload = api("POST", "/uploads", {
        "takes": [{"name": args.video.name, "size": args.video.stat().st_size}],
        "intent": args.intent,
    })
    upload_id = upload["id"]
    offset = upload.get("received", [0])[0]
    with args.video.open("rb") as video:
        video.seek(offset)
        while True:
            chunk = video.read(upload["chunk_bytes"])
            if not chunk:
                break
            api("PUT", f"/uploads/{upload_id}/takes/0?offset={offset}", chunk)
            offset += len(chunk)
            print(f"Uploaded {offset} bytes", file=sys.stderr)
    project = api("POST", f"/uploads/{upload_id}/complete")
    project_id = project["id"]
    print(f"Project: {project_id}", file=sys.stderr)
    deadline = time.monotonic() + args.timeout
    while project["status"] != "ready":
        if project["status"] == "failed":
            raise RuntimeError(project.get("error") or "The edit failed. Open the project in TakeAI to retry.")
        if time.monotonic() >= deadline:
            raise RuntimeError(f"Timed out waiting. Your video is still in TakeAI: {project_id}")
        print(project["status"], file=sys.stderr)
        time.sleep(3)
        project = api("GET", f"/projects/{project_id}")
    # Exclusive creation avoids overwriting another file, even if it appeared
    # while the edit was processing. Remove only our partial download on error.
    with request("GET", f"/projects/{project_id}/media/output") as response:
        output = args.output.open("xb")
        try:
            with output:
                while chunk := response.read(1024 * 1024):
                    output.write(chunk)
        except BaseException:
            args.output.unlink(missing_ok=True)
            raise
    print(f"Saved {args.output}")


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError) as error:
        raise SystemExit(str(error))
