#!/usr/bin/env python3
"""Taan API requests, file uploads, and downloads. Requires Python 3.12+.

Set TAAN_API_KEY before use. Text to music:
  python client.py POST /api/v1/music/text --body text.json --idempotency-key YOUR_SAVED_TEXT_KEY
  python client.py GET /api/v1/jobs/JOB_ID --download score.wav

Video or script:
  python client.py POST /api/v1/music/intents --body intent.json --idempotency-key YOUR_UNIQUE_KEY > intent-response.json
  python client.py upload intent-response.json INPUT_ID clip.mp4
  python client.py POST /api/v1/music/input --body input.json
  python client.py GET /api/v1/jobs/JOB_ID
  python client.py GET /api/v1/jobs/JOB_ID --download score.wav

Refinement:
  python client.py POST /api/v1/music/refine --body refine.json --idempotency-key YOUR_SAVED_REFINE_KEY

MIDI to music (caption: one nonblank line, at most 256 characters):
  python client.py POST /api/v1/music/midi/intents --body midi-intent.json > midi-response.json
  python client.py upload midi-response.json ASSET_ID score.mid
  python client.py POST /api/v1/music/intents/PROJECT_ID/midi-assets/ASSET_ID/complete
  python client.py GET /api/v1/music/intents/PROJECT_ID/midi-assets/ASSET_ID
  python client.py POST /api/v1/music/midi --body midi.json

Use the request bodies in https://taan.ai/docs/api/. Save each response's IDs.
Wait for MIDI status ready before conversion and job status succeeded before
downloading. These requests use credits. No requests are automatically retried.
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
import sys
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirect(HTTPRedirectHandler):
    # urllib's redirect callback receives dynamic response objects. Reject all redirects.
    def redirect_request(
        self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str
    ) -> None:
        return None


def json_object(value: object) -> dict[str, object]:
    if not isinstance(value, dict) or not all(isinstance(k, str) for k in value):
        raise ValueError("Expected a JSON object")
    return value


def transfer_url(value: object) -> str:
    if not isinstance(value, str):
        raise ValueError("Missing upload or download URL")
    url = urlsplit(value)
    if (
        url.scheme != "https"
        or url.hostname != "storage.googleapis.com"
        or url.port not in (None, 443)
        or url.username
        or url.password
        or url.fragment
    ):
        raise ValueError("Unexpected upload or download URL")
    return value


def api_request(
    method: str, path: str, body: Path | None = None, idempotency_key: str | None = None
) -> object:
    base = os.environ.get("TAAN_API_BASE_URL", "https://api.taan.ai").rstrip("/")
    origin = urlsplit(base)
    if (
        origin.scheme != "https"
        or not origin.hostname
        or origin.username
        or origin.password
        or origin.path
        or origin.query
        or origin.fragment
    ):
        raise ValueError("TAAN_API_BASE_URL must be an HTTPS origin")
    parsed = urlsplit(path)
    if (
        not path.startswith("/api/v1/")
        or parsed.scheme
        or parsed.netloc
        or parsed.fragment
        or "\\" in path
        or any(part in (".", "..") for part in parsed.path.split("/"))
    ):
        raise ValueError("Use a relative /api/v1/ path")
    key = os.environ.get("TAAN_API_KEY", "")
    if not key or any(c.isspace() for c in key):
        raise ValueError("Set TAAN_API_KEY to a valid API key")
    if method not in {"GET", "POST"} or (method == "GET" and body is not None):
        raise ValueError("Use GET without a body, or POST")
    raw = body.read_bytes() if body is not None else None
    if raw is not None:
        json_object(json.loads(raw))
    headers = {
        "Authorization": "Bearer " + key,
        "Accept": "application/json",
        "User-Agent": "Taan-Python-Client/1.0",
    }
    if method == "POST" and path == "/api/v1/music/text" and idempotency_key is None:
        raise ValueError("Text generation requires a saved --idempotency-key")
    if idempotency_key is not None:
        if (
            method != "POST"
            or path not in {"/api/v1/music/intents", "/api/v1/music/text", "/api/v1/music/refine"}
            or not 1 <= len(idempotency_key) <= 128
            or any(not "!" <= char <= "~" for char in idempotency_key)
        ):
            raise ValueError("Use a 1–128 character printable idempotency key for text, intents, or refinement")
        headers["Idempotency-Key"] = idempotency_key
    if raw is not None:
        headers["Content-Type"] = "application/json"
    request = Request(base + path, data=raw, headers=headers, method=method)
    with build_opener(NoRedirect()).open(request, timeout=60) as response:
        # JSON is deliberately dynamic here; each transfer validates its required fields.
        return json.loads(response.read())


def upload_file(response_file: Path, input_id: str, source: Path) -> None:
    response = json_object(json.loads(response_file.read_text()))
    entries = response.get("uploads")
    identifier_field = "input_id"
    if isinstance(entries, list):
        targets = [json_object(entry) for entry in entries]
        matching = [entry for entry in targets if entry.get("input_id") == input_id]
        if len(matching) != 1 or matching[0].get("method") != "PUT":
            raise ValueError("Expected one matching PUT upload target")
        target = matching[0]
    else:
        asset = json_object(response.get("asset"))
        if asset.get("id") != input_id:
            raise ValueError("MIDI asset ID does not match the registration")
        target = json_object(response.get("upload"))
        identifier_field = "asset_id"
    url = transfer_url(target.get("url"))
    raw_headers = json_object(target.get("headers"))
    headers: dict[str, str] = {}
    for name, value in raw_headers.items():
        if (
            not isinstance(value, str)
            or (name.lower() != "content-type" and not name.lower().startswith("x-goog-"))
            or any(c in name + value for c in "\r\n")
        ):
            raise ValueError("Unexpected upload header")
        headers[name] = value
    size = source.stat().st_size
    expected = next((v for k, v in headers.items() if k.lower() == "x-goog-content-length-range"), None)
    if expected != f"{size},{size}":
        raise ValueError("File size differs from the declared upload size")
    headers["Content-Length"] = str(size)
    with source.open("rb") as stream:
        request = Request(url, data=stream, headers=headers, method="PUT")
        with build_opener(NoRedirect()).open(request, timeout=300) as result:
            if result.status not in (200, 201):
                raise ValueError("Upload did not succeed")
    print(json.dumps({identifier_field: input_id, "uploaded": True}))


def download_file(response: object, destination: Path) -> None:
    job = json_object(response)
    if job.get("status") != "succeeded":
        raise ValueError("Wait for a succeeded job before downloading")
    result = json_object(job.get("result"))
    artifacts = result.get("artifacts")
    if not isinstance(artifacts, list):
        raise ValueError("Job result must contain an artifacts array")
    entries = [json_object(artifact) for artifact in artifacts]
    mixes = [artifact for artifact in entries if artifact.get("kind") == "full_mix"]
    if len(mixes) != 1:
        raise ValueError("Expected one full-mix artifact")
    url = transfer_url(mixes[0].get("url"))
    with build_opener(NoRedirect()).open(Request(url), timeout=300) as source:
        with destination.open("xb") as output:
            shutil.copyfileobj(source, output)


def main() -> int:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    commands = parser.add_subparsers(dest="command", required=True)
    for method in ("GET", "POST"):
        request = commands.add_parser(method)
        request.add_argument("path", help="Relative /api/v1/ path")
        if method == "POST":
            request.add_argument("--body", type=Path, help="JSON request file")
            request.add_argument("--idempotency-key", help="Saved key for text, intent creation, or refinement; reuse with the same body")
        else:
            request.add_argument("--download", type=Path, help="Save a succeeded job's full mix to a new file")
    upload = commands.add_parser("upload")
    upload.add_argument("response_file", type=Path)
    upload.add_argument("input_id", help="Input ID for file inputs, or asset ID for a MIDI registration")
    upload.add_argument("source", type=Path)
    args = parser.parse_args()
    try:
        if args.command == "upload":
            upload_file(args.response_file, args.input_id, args.source)
        else:
            result = api_request(
                args.command, args.path, getattr(args, "body", None),
                getattr(args, "idempotency_key", None),
            )
            destination = getattr(args, "download", None)
            if destination is not None:
                download_file(result, destination)
            else:
                print(json.dumps(result, indent=2))
    except HTTPError as error:
        # Error URLs can contain signed credentials; report only the status.
        print(f"HTTP {error.code}. Check the saved job and retry rules before repeating a POST.", file=sys.stderr)
        retry_after = error.headers.get("Retry-After", "") if error.headers else ""
        if error.code == 429 and retry_after.isascii() and retry_after.isdigit():
            print(f"Wait at least {retry_after} seconds before retrying the same request.", file=sys.stderr)
        return 1
    except (OSError, URLError, ValueError) as error:
        print(f"Request could not be completed ({type(error).__name__}). Check inputs and status before retrying.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
