import base64
import getpass
import json
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import uuid
import webbrowser

URL = 'https://yyds.seqnode.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent'
PAYLOAD = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "一只戴蓝色围巾的白色小狐狸，浅灰背景，柔和光线，无文字。"
                }
            ]
        }
    ],
    "generationConfig": {
        "responseModalities": [
            "IMAGE"
        ],
        "imageConfig": {
            "aspectRatio": "1:1",
            "imageSize": "4K"
        }
    }
}


def main():
    api_key = getpass.getpass("输入 API Key：").strip()
    if not api_key:
        raise ValueError("请输入有效的 API Key。")
    headers = {"x-goog-api-key": api_key}
    headers["Content-Type"] = "application/json; charset=utf-8"
    headers["User-Agent"] = "YM2API-Quickstart/1.0"
    request = Request(URL, data=json.dumps(PAYLOAD, ensure_ascii=False).encode("utf-8"), headers=headers)
    with urlopen(request, timeout=300) as response:
        result = json.load(response)
    parts = [part
        for candidate in result.get("candidates", [])
        for part in candidate.get("content", {}).get("parts", [])
        if not part.get("thought")]
    encoded = next((p["inlineData"]["data"] for p in parts if p.get("inlineData", {}).get("data")), None)
    link = next((p["fileData"]["fileUri"] for p in parts if p.get("fileData", {}).get("fileUri")), None)
    if encoded:
        data = base64.b64decode(encoded, validate=True)
    elif link:
        # 139 分组默认返回图片链接，1 小时内有效
        with urlopen(Request(link, headers={"User-Agent": "YM2API-Quickstart/1.0"}), timeout=120) as image:
            data = image.read()
    else:
        raise ValueError("响应没有最终图片。请检查响应和使用记录，再决定是否重试。")
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        extension = ".png"
    elif data.startswith(b"\xff\xd8\xff"):
        extension = ".jpg"
    elif len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        extension = ".webp"
    else:
        raise ValueError("返回数据不是可识别的 PNG、JPEG 或 WebP。")
    path = Path.cwd() / ("banana-2-" + uuid.uuid4().hex + extension)
    with path.open("xb") as output:
        output.write(data)
    print(f"图片已保存：{path}")
    if not webbrowser.open(path.as_uri()):
        print("请到以上路径手动打开图片。")


if __name__ == "__main__":
    try:
        main()
    except HTTPError as error:
        print(f"HTTP {error.code}：{error.read(2000).decode('utf-8', errors='replace')}")
        raise SystemExit(1)
    except Exception as error:
        print(f"运行失败：{error}")
        raise SystemExit(1)
