#!/usr/bin/env python3
"""Single otz.si request; no retries, redirects, client configuration, or key storage."""
import argparse
import getpass
import json
import os
import re
import sys
import urllib.error
import urllib.request


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward credentials to a redirected origin.


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", help="e.g. /v1/models")
    parser.add_argument("--json", dest="body_file", help="JSON request file; makes one POST")
    parser.add_argument("--allow-charge", action="store_true")
    parser.add_argument("--out", help="save result to a new file; never overwrites")
    args = parser.parse_args()
    posts = {"/v1/responses", "/v1/chat/completions", "/v1/messages", "/v1/images/generations", "/v1/videos"}
    gets = args.path == "/v1/models" or re.fullmatch(r"/v1/videos/[A-Za-z0-9_-]+(?:/content)?", args.path)
    if not ((args.body_file and args.path in posts) or (not args.body_file and gets)):
        parser.error("Unsupported method/path. Use the documented /v1 endpoints.")
    if args.path.endswith("/content") and not args.out:
        parser.error("Use --out video.mp4 for video content.")
    if args.out and os.path.lexists(args.out):
        parser.error("Output already exists; choose a new filename before sending.")
    payload = None
    if args.body_file:
        with open(args.body_file, encoding="utf-8") as source:
            body = json.load(source)
        if not isinstance(body, dict) or body.get("stream") is True:
            parser.error("Only non-streaming JSON objects are supported by this small example.")
        if "YOUR_MODEL_ID" in str(body.get("model", "")):
            parser.error("Replace YOUR_MODEL_ID with a model allowed by your key.")
        if not args.allow_charge:
            parser.error("Generation may charge money; explicit --allow-charge is required.")
        if input("One request may incur charges; no automatic retry. Type GENERATE to continue: ") != "GENERATE":
            return
        payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
    key = getpass.getpass("Your otz.si API key (hidden): ").strip()
    if not key or any(char.isspace() for char in key):
        parser.error("The key must be nonempty without whitespace.")
    headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
    if args.path == "/v1/messages":
        headers["anthropic-version"] = "2023-06-01"
    request = urllib.request.Request("https://otz.si" + args.path, data=payload, headers=headers)
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=300) as response:
            print("HTTP", response.status, "request_id:", response.headers.get("X-Oneapi-Request-Id", "unavailable"))
            if args.out:
                fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
                with os.fdopen(fd, "wb") as output:
                    while chunk := response.read(1024 * 1024):
                        output.write(chunk)
                print("Saved locally. Keep the result private.")
            else:
                print(response.read().decode("utf-8"))
    except urllib.error.HTTPError as error:
        print("HTTP", error.code, "request_id:", error.headers.get("X-Oneapi-Request-Id", "unavailable"), file=sys.stderr)
        print("No retry was sent. Check the request status before generating again.", file=sys.stderr)
        sys.exit(1)
    except (OSError, urllib.error.URLError):
        print("Connection or local save failed; the task may have been accepted. Do not blindly retry.", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
