#!/usr/bin/env python3
"""
OCR Sadi-176-180 với Qwen3-VL-235B-A22B-Instruct - Gửi từng trang
"""

import base64
import os
import requests
from PIL import Image
import io
import time

start_time = time.time()

API_KEY = os.environ.get("OPENROUTER_API_KEY")
if not API_KEY:
    print("❌ Thiếu OPENROUTER_API_KEY")
    exit(1)

WORKDIR = "/opt/openclaw/.openclaw/workspace/Chuan Muc Sadi"

all_text = []

for i in range(1, 6):
    print(f"\n🔄 Xử lý trang {i}/5...")
    
    img_path = f"{WORKDIR}/sadi_page-{i}.png"
    
    # Resize ảnh
    with Image.open(img_path) as img:
        ratio = 1200 / img.width
        new_height = int(img.height * ratio)
        img_resized = img.resize((1200, 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"   Đã encode trang {i}")
    
    # Prompt
    prompt = f"""Extract all Myanmar text from this PDF page exactly as written. Preserve ALL characters, diacritics, spacing, and formatting. Do NOT clean, modify, or autocorrect anything. This is a literal transcription.

Output ONLY the Myanmar text, no English explanations."""
    
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_data}"}}
            ]
        }
    ]
    
    payload = {
        "model": "openrouter/Qwen3-VL-235B-A22B-Instruct",
        "messages": messages,
        "max_tokens": 2048,
        "temperature": 0.1
    }
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://openclaw.ai",
        "X-Title": "OpenClaw OCR"
    }
    
    try:
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers=headers,
            json=payload,
            timeout=120
        )
        
        if response.status_code == 200:
            result = response.json()
            text = result["choices"][0]["message"]["content"]
            all_text.append(f"--- Trang {i} ---\n{text}")
            print(f"   ✅ Trang {i} hoàn thành: {len(text)} ký tự")
        else:
            print(f"   ❌ Lỗi trang {i}: {response.status_code}")
            print(f"   {response.text[:200]}")
            all_text.append(f"--- Trang {i} ---\n[OCR FAILED: {response.status_code}]")
    except Exception as e:
        print(f"   ❌ Exception trang {i}: {e}")
        all_text.append(f"--- Trang {i} ---\n[OCR EXCEPTION: {str(e)}]")

# Lưu kết quả
if all_text:
    output_path = f"{WORKDIR}/extracted/Sadi-176-180-qwen.md"
    with open(output_path, "w", encoding="utf-8") as f:
        f.write("\n\n".join(all_text))
    
    elapsed = time.time() - start_time
    print(f"\n✅ OCR hoàn thành! Đã lưu vào: {output_path}")
    total_chars = sum(len(t) for t in all_text)
    print(f"📊 Tổng: {total_chars} ký tự")
    print(f"⏱️ Thời gian: {elapsed:.1f} giây")
