#!/usr/bin/env python3
"""One paid Suno request, durable receipt, bounded polling and audio download.
Python 3.10+, standard library only. Keys never enter saved receipts or media requests.
"""
import argparse
import json
import os
from pathlib import Path
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid


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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--generate", action="store_true", help="Create one paid task; uses an idempotency key")
    parser.add_argument("--task-id", help="Resume polling an existing task without a new charge")
    parser.add_argument("--receipt", default="suno-receipt.json")
    parser.add_argument("--out", default="suno-output")
    parser.add_argument("--timeout", type=int, default=900)
    parser.add_argument("--prompt", default="Warm acoustic folk with brushed drums and gentle piano for a quiet morning scene")
    args = parser.parse_args()
    if not args.generate and not args.task_id:
        parser.error("Use --generate for one paid request, or --task-id to resume")
    if args.generate and args.task_id:
        parser.error("Choose --generate or --task-id")
    if not 1 <= args.timeout <= 3600:
        parser.error("--timeout must be between 1 and 3600 seconds")
    key = os.environ.get("API_STOCK_KEY")
    if not key:
        parser.error("Set API_STOCK_KEY in your server environment")
    origin = os.environ.get("API_STOCK_ORIGIN", "https://api.api-stock.com").rstrip("/")
    parsed = urllib.parse.urlsplit(origin)
    if parsed.path or parsed.query or parsed.fragment or parsed.username or not (
        parsed.scheme == "https" and parsed.hostname in {"api.api-stock.com", "api.apihubs.ru"}
        or parsed.scheme == "http" and parsed.hostname in {"127.0.0.1", "localhost"}
    ):
        parser.error("Use an official API origin or a local test server")
    opener = urllib.request.build_opener(NoRedirect())

    def api(path, body=None, request_key=None):
        headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json",
                   "User-Agent": "APIStockPythonExample/1.0"}
        if request_key:
            headers["Idempotency-Key"] = request_key
        req = urllib.request.Request(origin + "/api/v1" + path, headers=headers,
                                     data=json.dumps(body).encode() if body is not None else None)
        try:
            with opener.open(req, timeout=30) as response:
                value = json.load(response)
        except urllib.error.HTTPError as error:
            raise RuntimeError("API HTTP " + str(error.code) + "; check your key, balance and request") from None
        return value.get("data", value)

    receipt_path = Path(args.receipt)
    task_id = args.task_id
    if args.generate:
        if receipt_path.exists():
            saved = json.loads(receipt_path.read_text())
            if saved.get("origin") != origin:
                raise RuntimeError("Receipt belongs to another origin; choose a separate receipt")
        else:
            saved = {"origin": origin, "idempotencyKey": str(uuid.uuid4()), "request": {
                "model": "suno", "input": {"action": "music", "custom": False,
                "gptDescriptionPrompt": args.prompt, "makeInstrumental": True, "maxMode": False}}}
            # Exclusive creation saves the retry identity before the paid POST.
            with receipt_path.open("x") as handle:
                json.dump(saved, handle, indent=2)
        task_id = saved.get("taskId")
        if not task_id:
            result = api("/generation/create-idempotent", saved["request"], saved["idempotencyKey"])
            task_id = result.get("taskId")
            if not task_id:
                raise RuntimeError("No taskId; retain the receipt and retry with the same file")
            saved["taskId"] = task_id
            temp = receipt_path.with_suffix(receipt_path.suffix + ".tmp")
            temp.write_text(json.dumps(saved, indent=2))
            temp.replace(receipt_path)
    print("Task:", task_id, "— keep this ID and receipt to resume")
    deadline = time.monotonic() + args.timeout
    while time.monotonic() < deadline:
        result = api("/task/status/" + urllib.parse.quote(task_id, safe=""))
        status = str(result.get("status", "")).lower()
        if status in {"failed", "expired"}:
            raise RuntimeError("Task ended with status " + status + "; no automatic paid retry")
        if status == "finished":
            output = Path(args.out)
            output.mkdir(parents=True, exist_ok=True)
            (output / "result.json").write_text(json.dumps(result, indent=2))
            files = result.get("files", [])
            if not files:
                raise RuntimeError("Finished task returned no files")
            for index, item in enumerate(files):
                file_url = item.get("fileUrl", "")
                url = urllib.parse.urlsplit(file_url)
                if url.scheme != "https" or not url.hostname:
                    raise RuntimeError("Expected an HTTPS media URL")
                # No Authorization header is sent to the media host.
                with urllib.request.urlopen(file_url, timeout=60) as response:
                    (output / ("track-" + str(index + 1) + (Path(url.path).suffix if Path(url.path).suffix.lower() in {".mp3", ".wav", ".flac", ".ogg", ".m4a"} else ".bin"))).write_bytes(response.read())
            print("Saved", len(files), "file(s) to", output)
            return
        time.sleep(3)
    raise RuntimeError("Polling timed out; resume with --task-id " + task_id + ". Do not create a replacement task.")


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