#!/usr/bin/env python3
"""
OCR với Gemini 2.5 Pro - Ảnh rất nhỏ (200px, JPEG)
"""

import base64
import os
import urllib.request
import json
import time
from PIL import Image
import io

API_KEY = os.environ.get("GEMINI_API_KEY")
WORKDIR = "/opt/openclaw/.openclaw/workspace/Chuan Muc Sadi"
GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent?key={API_KEY}"

print("📖 Test với ảnh 200px JPEG...", flush=True)

img_path = f"{WORKDIR}/sadi_page-1.png"

with Image.open(img_path) as img:
    ratio = 200 / img.width
    new_height = int(img.height * ratio)
    img_resized = img.resize((200, new_height), Image.LANCZOS)
    
    buffer = io.BytesIO()
    img_resized.save(buffer, format="JPEG", quality=75)
    img_data = base64.b64encode(buffer.getvalue()).decode("utf-8")

print(f"   JPEG base64: {len(img_data)} chars", flush=True)

payload = {
    "contents": [{
        "parts": [
            {"text": "Extract ALL Myanmar text exactly as written. Output ONLY Myanmar text."},
            {"inline_data": {"mime_type": "image/jpeg", "data": img_data}}
        ]
    }],
    "generationConfig": {"temperature": 0.1, "maxOutputTokens": 2048}
}

print("   Sending...", flush=True)
start = time.time()
req = urllib.request.Request(GEMINI_URL, data=json.dumps(payload).encode('utf-8'), headers={'Content-Type': 'application/json'}, method='POST')

try:
    with urllib.request.urlopen(req, timeout=90) as response:
        elapsed = time.time() - start
        result = json.loads(response.read().decode('utf-8'))
        print(f"   Response in {elapsed:.1f}s", flush=True)
        text = result["candidates"][0]["content"]["parts"][0]["text"]
        print(f"\n✅ Result ({len(text)} chars):\n{text}", flush=True)
except Exception as e:
    print(f"   ❌ {e}", flush=True)
