#!/usr/bin/env python3
"""Deskripsi detail produk atap dari foto Bos — retry loop."""
import base64, json, time, urllib.request

KEYFILE = '/home/mantapman/.openrouter_key'
with open(KEYFILE) as f:
    KEY = f.read().strip()
IMG = 'media/inbound/openclaw-staged-2113896e-b8ab-44ef-886f-a7ebfb241f29/8936ecf6-18d3-4f68-b8f8-77c17f9d17e3.jpg'

with open(IMG, 'rb') as f:
    b64 = base64.b64encode(f.read()).decode()

PROMPT = ("Ini foto PRODUK ATAP (roofing) — amati dengan teliti. Deskripsikan SANGAT DETAIL dalam Bahasa Indonesia:\n"
          "1) Bentuk & profil atapnya (gelombang? flat? jumlah gelombang, pola)\n"
          "2) Warna utama & warna aksen\n"
          "3) Material (metal, spandek, zincalume?)\n"
          "4) Tekstur/pola, sudut atap lurus/dipotong\n"
          "5) Latar belakang & setting foto\n"
          "6) Ada teks/logo/branding? Tulis persis.\n"
          "Jawab detail per poin.")

for attempt in range(4):
    body = {
        "model": "nvidia/nemotron-nano-12b-v2-vl:free",
        "max_tokens": 700,
        "messages": [{"role": "user", "content": [
            {"type": "text", "text": PROMPT},
            {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}
        ]}]
    }
    req = urllib.request.Request("https://openrouter.ai/api/v1/chat/completions",
        data=json.dumps(body).encode(),
        headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=180) as r:
            d = json.loads(r.read())
        if "choices" in d:
            print(d["choices"][0]["message"]["content"])
            break
        else:
            print(f"[{attempt}] no choices:", json.dumps(d)[:200])
    except Exception as e:
        print(f"[{attempt}] ERROR:", str(e)[:200])
    time.sleep(10)
