#!/usr/bin/env python3
"""
OCR Sadi-151-155 với Qwen3-VL-235B-A22B-Instruct qua OpenRouter API
"""

import base64
import json
import os
import requests

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"

# Encode ảnh sang base64
images_base64 = []
for i in range(1, 6):
    img_path = f"{WORKDIR}/sadi_page-{i}.png"
    with open(img_path, "rb") as f:
        img_data = base64.b64encode(f.read()).decode("utf-8")
        images_base64.append(f"data:image/png;base64,{img_data}")
    print(f"✅ Đã encode trang {i}")

# Prompt OCR
prompt = """Extract all Myanmar text from these PDF pages exactly as written. Preserve ALL characters, diacritics, spacing, and formatting. Do NOT clean, modify, or autocorrect anything. This is a literal transcription.

Output the text in markdown format with proper structure."""

# Build request
messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": prompt},
            *[{"type": "image_url", "image_url": {"url": img}} for img in images_base64]
        ]
    }
]

payload = {
    "model": "openrouter/Qwen3-VL-235B-A22B-Instruct",
    "messages": messages,
    "max_tokens": 4096,
    "temperature": 0.1
}

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "HTTP-Referer": "https://openclaw.ai",
    "X-Title": "OpenClaw OCR"
}

print("🔄 Đang gọi OpenRouter API...")
response = requests.post(
    "https://openrouter.ai/api/v1/chat/completions",
    headers=headers,
    json=payload,
    timeout=300
)

if response.status_code == 200:
    result = response.json()
    text = result["choices"][0]["message"]["content"]
    
    output_path = f"{WORKDIR}/extracted/Sadi-151-155-qwen-raw.md"
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(text)
    
    print(f"✅ OCR hoàn thành! Đã lưu vào: {output_path}")
    print(f"📊 Độ dài: {len(text)} ký tự")
else:
    print(f"❌ Lỗi API: {response.status_code}")
    print(response.text)
