#!/usr/bin/env python3
"""Quick test: can this OpenAI API key generate images?

Usage:
  export OPENAI_API_KEY="sk-..."
  python3 openai_image_test.py "A cute blue robot mascot, clean white background"

Output:
  Saves generated image to ./openai_image_test.png
"""

import base64
import os
import sys
from pathlib import Path

try:
    from openai import OpenAI
except ImportError:
    print("Missing package: openai")
    print("Install it with: pip install openai")
    sys.exit(1)


def main() -> int:
    api_key = os.getenv("OPENAI_API_KEY")
    if not api_key:
        print("OPENAI_API_KEY is not set.")
        print('Run: export OPENAI_API_KEY="your_api_key_here"')
        return 1

    prompt = " ".join(sys.argv[1:]).strip()
    if not prompt:
        prompt = "A simple cute blue robot mascot, clean white background, friendly, high quality digital art"

    client = OpenAI(api_key=api_key)

    print("Testing OpenAI image generation access...")
    print(f"Prompt: {prompt}")

    try:
        result = client.images.generate(
            model="gpt-image-1",
            prompt=prompt,
            size="1024x1024",
        )
    except Exception as e:
        print("\nImage generation failed.")
        print(f"Error type: {type(e).__name__}")
        print(f"Error: {e}")
        print("\nCommon meanings:")
        print("- model_not_found / no access: your API account may not have gpt-image-1 access")
        print("- insufficient_quota: billing/quota issue")
        print("- invalid_api_key: wrong or expired API key")
        print("- billing not enabled: add API billing at platform.openai.com")
        return 2

    data = result.data[0]
    out_path = Path("openai_image_test.png")

    if getattr(data, "b64_json", None):
        out_path.write_bytes(base64.b64decode(data.b64_json))
        print(f"\nSuccess. Image saved to: {out_path.resolve()}")
        return 0

    if getattr(data, "url", None):
        print("\nSuccess. Image URL:")
        print(data.url)
        return 0

    print("\nThe request succeeded, but no b64_json or url was returned.")
    print(data)
    return 3


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