#!/usr/bin/env python3
"""Resumable Audio Cleaner example, Python 3.11+; standard library only."""
import argparse
import base64
import hashlib
import json
import mimetypes
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, build_opener, HTTPRedirectHandler
from uuid import uuid4

OPERATIONS = ("denoise_audio", "denoise_video", "inspect_media", "analyze_audio", "generate_waveform")
BASE = "https://gateway.apibasket.com/media/audio-cleaner"
PART_SIZE = 8388608


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


OPENER = build_opener(NoRedirect())


def open_request(url, *, method="GET", body=None, headers=None):
    parsed = urlsplit(url)
    if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
        raise RuntimeError("Only verified HTTPS URLs are accepted")
    # Do not put a URL or exception object in a log: it may contain a ticket.
    try:
        return OPENER.open(Request(url, data=body, headers=headers or {}, method=method), timeout=120)
    except HTTPError as error:
        code = error.code
        error.close()
        raise RuntimeError(f"HTTP {code}; query the same task or retry the same intent") from None
    except OSError:
        raise RuntimeError("Request outcome unknown; resume using the same saved intent") from None


def call(action, *, body=None, query=None, key=None):
    token = os.environ.get("API_BASKET_KEY", "")
    if not token:
        raise RuntimeError("Set API_BASKET_KEY privately")
    headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
               "X-API-Version": os.environ.get("AUDIO_CLEANER_API_VERSION", "1.0.0"),
               "X-Function-Version": os.environ.get("AUDIO_CLEANER_FUNCTION_VERSION", "1.0.0")}
    if os.environ.get("AUDIO_CLEANER_RELEASE"):
        headers["X-API-Release"] = os.environ["AUDIO_CLEANER_RELEASE"]
    if key:
        headers["Idempotency-Key"] = key
    raw = None
    if body is not None:
        raw = json.dumps(body, separators=(",", ":")).encode()
        headers["Content-Type"] = "application/json"
    with open_request(BASE + "/" + action + ("?" + urlencode(query) if query else ""),
                      method="POST" if body is not None else "GET", body=raw, headers=headers) as response:
        raw = response.read(2 * 1024 * 1024 + 1)
    if len(raw) > 2 * 1024 * 1024:
        raise RuntimeError("Unexpected response size")
    result = json.loads(raw)
    if "resp" in result and "precharge_credit" in result and "request_received_at" in result:
        result = result["resp"]
    if isinstance(result, dict) and "data" in result:
        result = result["data"]
    return result


def save(path, state):
    # Atomic replacement persists intent before a network operation. No URLs/keys
    # from responses, API credentials or file contents enter this state.
    path = Path(path)
    temp = path.with_name(path.name + ".tmp")
    fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as output:
        json.dump(state, output, indent=2)
        output.flush()
        os.fsync(output.fileno())
    temp.replace(path)


def mutation_key(state, path, action):
    keys = state.setdefault("keys", {})
    if action not in keys:
        keys[action] = str(uuid4())
        save(path, state)
    return keys[action]


def fingerprint(path):
    hasher = hashlib.sha256()
    with Path(path).open("rb") as source:
        while chunk := source.read(PART_SIZE):
            hasher.update(chunk)
    return hasher.hexdigest()


def upload(state, path, filename):
    file = Path(filename)
    if (file.name != state["file_name"] or file.stat().st_size != state["file_size_bytes"]
            or fingerprint(file) != state["sha256"]):
        raise RuntimeError("Select the unchanged original file")
    print("Upload reservation: 50 credits once. Successful fee uses verified complete input duration/channels.")
    with file.open("rb") as source:
        for number in range(1, state["part_count"] + 1):
            data = source.read(PART_SIZE)
            md5 = base64.b64encode(hashlib.md5(data, usedforsecurity=False).digest()).decode()
            response = call("upload_parts", body={"task_id": state["task_id"],
                "parts": [{"part_number": number, "content_md5": md5}]})
            parts = response["parts"]
            if len(parts) != 1 or parts[0]["part_number"] != number:
                raise RuntimeError("Unexpected upload credentials")
            part = parts[0]
            with open_request(part["url"], method="PUT", body=data, headers=part["headers"]):
                pass
            print(f"Uploaded part {number}/{state['part_count']}")
    call("upload_complete", body={"task_id": state["task_id"]},
         key=mutation_key(state, path, "complete"))


def task(state):
    return call("get_task", query={"task_id": state["task_id"]})


def inspect(state):
    result = task(state)
    while result["task"]["status"] in {"QUEUED", "RUNNING"}:
        print(result["task"]["status"], result["task"]["progress"])
        time.sleep(4)
        result = task(state)
    print("Task:", state["task_id"], result["task"]["status"])
    if usage := result.get("usage"):
        print("Verified usage:", json.dumps(usage))
        operation = state["operation"]
        amount = (10 if operation == "inspect_media" else usage["billable_channel_minutes"] * 15
                  if operation == "analyze_audio" else usage["billable_channel_minutes"] * 10
                  if operation == "generate_waveform" else usage["billable_minutes"] * 50)
        print("Successful processing fee:", amount, "credits")
    elif result["task"]["status"] in {"READY", "COMPLETED"}:
        raise RuntimeError("Missing successful usage; do not infer a zero charge")
    return result


def claim(state, path, result, download_dir):
    if result["task"]["status"] not in {"READY", "COMPLETED"}:
        raise RuntimeError("No successful result is available")
    links = call("download_links", body={"task_id": state["task_id"]},
                 key=mutation_key(state, path, "claim"))
    print("Result credentials claimed; lifecycle slot released. No GET performed yet.")
    if not download_dir:
        return
    destination = Path(download_dir)
    destination.mkdir(parents=True, exist_ok=True)
    artifacts = {item["id"]: item for item in result["artifacts"]}
    for link in links["links"]:
        artifact = artifacts[link["artifact_id"]]
        name = artifact["file_name"]
        if Path(name).name != name or name in {".", ".."}:
            raise RuntimeError("Invalid result filename")
        target = destination / name
        if target.exists() and fingerprint(target) == artifact["sha256"]:
            print("Already verified:", target)
            continue
        temporary = destination / (name + ".partial")
        hasher, size = hashlib.sha256(), 0
        # Exactly one GET, no automatic stream retries. No API credentials here.
        with open_request(link["url"]) as response, temporary.open("wb") as output:
            while data := response.read(1024 * 1024):
                size += len(data)
                if size > artifact["size"]:
                    raise RuntimeError("Result exceeds advertised size")
                hasher.update(data)
                output.write(data)
        if size != artifact["size"] or hasher.hexdigest() != artifact["sha256"]:
            raise RuntimeError("Result SHA-256/size mismatch; partial file was not delivered")
        temporary.replace(target)
        print("SHA-256 verified:", target)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    for command in ("run", "resume", "cancel", "increase"):
        p = commands.add_parser(command)
        p.add_argument("--state", required=True, type=Path)
        if command in {"run", "resume"}:
            p.add_argument("--file" if command == "resume" else "file")
            p.add_argument("--upload", action="store_true", help="Authorize 50-credit reservation and successful processing fee")
            p.add_argument("--claim", action="store_true", help="Explicitly claim result credentials")
            p.add_argument("--download-dir", type=Path)
        if command == "run":
            p.add_argument("--operation", choices=OPERATIONS, required=True)
        if command == "increase":
            p.add_argument("--slots", type=int, required=True)
            p.add_argument("--steps", type=int, required=True)
            p.add_argument("--starts-at")
            p.add_argument("--confirm-credits", type=int, required=True)
    commands.add_parser("capabilities")
    args = parser.parse_args()
    if args.command == "capabilities":
        print(json.dumps(call("capabilities"), indent=2))
        return
    state = json.loads(args.state.read_text()) if args.state.exists() else {}
    if args.command == "increase":
        amount = args.slots * args.steps * 10000
        if not (1 <= args.slots <= 2147483647 and 1 <= args.steps <= 3650 and amount <= 999999999999
                and args.confirm_credits == amount):
            raise RuntimeError("Confirm the exact valid slot purchase cost")
        body = {"additional_slots": args.slots, "duration_steps": args.steps}
        if args.starts_at:
            body["starts_at"] = args.starts_at
        if state and state.get("purchase") != body:
            raise RuntimeError("Saved purchase intent differs; recover that intent first")
        state["purchase"] = body
        print("Immediate purchase cost:", amount, "credits")
        result = call("increase_concurrency", body=body, key=mutation_key(state, args.state, "purchase"))
        print(json.dumps(result, indent=2))
        return
    if args.command == "run":
        file = Path(args.file)
        body = {"file_name": file.name, "content_type": mimetypes.guess_type(file.name)[0] or "application/octet-stream",
                "file_size_bytes": file.stat().st_size}
        if not 1 <= body["file_size_bytes"] <= 1073741824:
            raise RuntimeError("Input exceeds the 1 GiB limit")
        intent = {**body, "operation": args.operation, "sha256": fingerprint(file)}
        if state and any(state.get(k) != v for k, v in intent.items()):
            raise RuntimeError("Saved task differs; resume it or choose a fresh state filename")
        state.update(intent)
        if not state.get("task_id"):
            response = call(args.operation, body=body, key=mutation_key(state, args.state, "create"))
            if response["part_size_bytes"] != PART_SIZE:
                raise RuntimeError("Unexpected part size")
            state.update(task_id=response["task"]["id"], part_count=response["part_count"])
            save(args.state, state)
            print("Task created for free:", state["task_id"])
    if not state.get("task_id"):
        raise RuntimeError("No saved task; run the create command first")
    if args.command == "cancel":
        result = call("cancel_task", body={"task_id": state["task_id"]}, key=mutation_key(state, args.state, "cancel"))
        print(json.dumps(result, indent=2))
        return
    result = task(state)
    if args.upload and result["task"]["status"] == "UPLOADING":
        if not args.file:
            raise RuntimeError("Use --file to select the original input")
        upload(state, args.state, args.file)
    result = inspect(state)
    if args.download_dir and not args.claim:
        raise RuntimeError("Use --claim with --download-dir to request the result explicitly")
    if args.claim:
        claim(state, args.state, result, args.download_dir)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Stopped locally. The task is still active; resume with the same state.", file=sys.stderr)
        sys.exit(130)
    except (RuntimeError, ValueError, KeyError, OSError):
        # Avoid accidentally serializing a signed URL, API credential or ticket.
        print("Request could not be completed. Preserve state and query the task before retrying; check credits, versions and file metadata.", file=sys.stderr)
        sys.exit(1)
