#!/usr/bin/env python3
"""
Test Gemini OCR với trang 1 - Debug version
"""

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 OCR trang 1...", flush=True)

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

# Resize ảnh nhỏ hơn
with Image.open(img_path) as img:
    ratio = 600 / img.width
    new_height = int(img.height * ratio)
    img_resized = img.resize((600, new_height), Image.LANCZOS)
    
    buffer = io.BytesIO()
    img_resized.save(buffer, format="PNG", optimize=True)
    img_data = base64.b64encode(buffer.getvalue()).decode("utf-8")

print(f"   Ảnh resize: 600px width, base64: {len(img_data)} chars", flush=True)

payload = {
    "contents": [{
        "parts": [
            {"text": "Extract all Myanmar text from this page EXACTLY as written. Output ONLY Myanmar text."},
            {"inline_data": {"mime_type": "image/png", "data": img_data}}
        ]
    }],
    "generationConfig": {
        "temperature": 0.1,
        "maxOutputTokens": 4096
    }
}

print("   Đang gửi request...", 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=180) as response:
        elapsed = time.time() - start
        result = json.loads(response.read().decode('utf-8'))
        print(f"   Response time: {elapsed:.1f}s", flush=True)
        print(f"   Full response: {json.dumps(result, indent=2)[:1000]}", flush=True)
        
        if "candidates" in result and len(result["candidates"]) > 0:
            text = result["candidates"][0]["content"]["parts"][0]["text"]
            print(f"\n✅ Kết quả ({len(text)} ký tự):\n", flush=True)
            print(text, flush=True)
        else:
            print("❌ No candidates in response", flush=True)
            
except urllib.error.HTTPError as e:
    print(f"   ❌ HTTP Error {e.code}: {e.read().decode()[:500]}", flush=True)
except Exception as e:
    print(f"   ❌ Error: {e}", flush=True)
