#!/usr/bin/env python3
"""
Gemini ile TABLO BAZLI Çeviri
Gemini'ye tabloyu zorla algılat, hücre hücre çevir
"""

import fitz
import json
import base64
import google.generativeai as genai

# API Key
GEMINI_API_KEY = "AIzaSyCkYVKLxWDPNbQZr0-HM0nlSneEeM9KMjs"

PROMPT = """Bu teknik doküman sayfasını analiz et. Sayfa bir TABLO içeriyor.

GÖREV:
1. Sayfadaki TÜM metin öğelerini bul (başlıklar, paragraflar, TABLO HÜCRELERİ)
2. TABLO HÜCRELERİNİ AYRI AYRI listele - her hücre ayrı bir item
3. Her öğe için KOORDİNAT ve TÜRKÇE ÇEVİRİ ver

KOORDİNAT SİSTEMİ:
- Sayfa sol üst köşesi (0, 0)
- Sayfa sağ alt köşesi (100, 100)
- Yüzde olarak ver (0-100 arası)

ÇEVİRİ KURALLARI:
- engine = motor
- pump = pompa  
- valve = valf
- brake = fren
- sensor = sensör
- controller = kontrol ünitesi
- actuator = aktüatör
- displacement = deplasman
- traction = çekiş
- min⁻¹ = dev/dk
- Hata kodları (111000, 111103) ve referanslar (T2-2, T/M) ÇEVİRME, aynen bırak
- "-" tek başına ise aynen bırak
- Boş hücreleri ATLAMA

ÇIKTI FORMATI (SADECE JSON, başka bir şey yazma):
{
  "cells": [
    {
      "text": "orijinal İngilizce metin",
      "translation": "Türkçe çeviri",
      "bbox": [x0, y0, x1, y1],
      "type": "header" | "cell" | "paragraph"
    }
  ]
}

ÖNEMLİ:
- Her TABLO HÜCRESİ ayrı bir item olmalı
- Hücreler birleştirilMEMELİ
- Koordinatlar DOĞRU olmalı (yüzde cinsinden 0-100)
- Sadece JSON döndür, açıklama yazma"""


def pdf_page_to_image(pdf_path: str, page_num: int = 0, dpi: int = 150) -> bytes:
    """PDF sayfasını PNG'ye çevir"""
    doc = fitz.open(pdf_path)
    page = doc.load_page(page_num)
    
    mat = fitz.Matrix(dpi/72, dpi/72)
    pix = page.get_pixmap(matrix=mat)
    
    img_bytes = pix.tobytes("png")
    
    page_width = page.rect.width
    page_height = page.rect.height
    
    doc.close()
    
    return img_bytes, page_width, page_height


def analyze_with_gemini(image_bytes: bytes) -> dict:
    """Gemini ile tablo analizi ve çeviri"""
    
    genai.configure(api_key=GEMINI_API_KEY)
    model = genai.GenerativeModel('gemini-2.0-flash')
    
    # Base64 encode
    img_base64 = base64.b64encode(image_bytes).decode()
    
    response = model.generate_content([
        {"mime_type": "image/png", "data": img_base64},
        PROMPT
    ])
    
    text = response.text
    
    # Debug - raw response kaydet
    with open("/tmp/gemini_table_response.txt", "w", encoding="utf-8") as f:
        f.write(text)
    
    try:
        if "```json" in text:
            json_str = text.split("```json")[1].split("```")[0].strip()
        elif "```" in text:
            json_str = text.split("```")[1].split("```")[0].strip()
        else:
            json_str = text.strip()
        
        return json.loads(json_str)
    
    except Exception as e:
        print(f"JSON parse hatası: {e}")
        print(f"İlk 500 karakter: {text[:500]}")
        return {"cells": []}


def apply_translations(pdf_path: str, data: dict, output_path: str, 
                       page_width: float, page_height: float, page_num: int = 0):
    """Çevirileri PDF'e uygula"""
    
    doc = fitz.open(pdf_path)
    page = doc.load_page(page_num)
    
    font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    
    applied = 0
    
    for cell in data.get("cells", []):
        text = cell.get("text", "")
        translation = cell.get("translation", "")
        bbox_pct = cell.get("bbox", [])
        cell_type = cell.get("type", "cell")
        
        # Boş veya aynı ise atla
        if not translation or translation == text:
            continue
        
        # Sadece sayı/kod ise atla
        if text.replace(" ", "").replace("-", "").replace(",", "").isdigit():
            continue
        
        if len(bbox_pct) != 4:
            continue
        
        # Yüzdeyi piksele çevir
        x0 = bbox_pct[0] * page_width / 100
        y0 = bbox_pct[1] * page_height / 100
        x1 = bbox_pct[2] * page_width / 100
        y1 = bbox_pct[3] * page_height / 100
        
        # Minimum boyut kontrolü
        if (x1 - x0) < 5 or (y1 - y0) < 5:
            continue
        
        rect = fitz.Rect(x0, y0, x1, y1)
        
        # Maskeleme
        page.draw_rect(rect, color=(1, 1, 1), fill=(1, 1, 1))
        
        # Font boyutu
        box_height = y1 - y0
        box_width = x1 - x0
        
        # Tip bazlı font
        if cell_type == "header":
            fontsize = min(11, max(7, box_height - 2))
        else:
            # Metin uzunluğuna göre
            char_width = 5
            chars_per_line = max(5, box_width / char_width)
            lines_needed = max(1, len(translation) / chars_per_line)
            fontsize = min(9, max(5, (box_height / lines_needed) - 1))
        
        # Metni yaz
        text_rect = fitz.Rect(x0 + 1, y0 + 1, x1 - 1, y1 - 1)
        
        try:
            rc = page.insert_textbox(
                text_rect,
                translation,
                fontsize=fontsize,
                fontname="dejavu",
                fontfile=font_path,
                color=(0, 0, 0),
                align=fitz.TEXT_ALIGN_LEFT
            )
            
            if rc >= 0:
                applied += 1
                print(f"   ✓ [{x0:.0f},{y0:.0f}] {translation[:30]}...")
            else:
                # Overflow - font küçült ve tekrar dene
                smaller_font = fontsize * 0.7
                page.draw_rect(rect, color=(1, 1, 1), fill=(1, 1, 1))
                page.insert_textbox(
                    text_rect,
                    translation,
                    fontsize=smaller_font,
                    fontname="dejavu",
                    fontfile=font_path,
                    color=(0, 0, 0),
                    align=fitz.TEXT_ALIGN_LEFT
                )
                applied += 1
                print(f"   ✓ [{x0:.0f},{y0:.0f}] (küçük font) {translation[:25]}...")
                
        except Exception as e:
            print(f"   ✗ Hata: {e}")
    
    doc.save(output_path)
    doc.close()
    
    return applied


def main():
    input_pdf = "/var/www/html/PEPCVSON/public/katalog/api/output/ZW140-5B_sayfa_315.pdf"
    output_pdf = "/var/www/html/PEPCVSON/public/katalog/api/output/ZW140-5B_sayfa_315_TABLE.pdf"
    
    print("📄 1/3 PDF görüntüye dönüştürülüyor...")
    img_bytes, page_width, page_height = pdf_page_to_image(input_pdf, 0, dpi=200)
    print(f"   Sayfa: {page_width:.0f} x {page_height:.0f} pt")
    
    print("\n🤖 2/3 Gemini ile tablo analizi...")
    data = analyze_with_gemini(img_bytes)
    
    cells = data.get("cells", [])
    print(f"   → {len(cells)} hücre/öğe bulundu")
    
    if not cells:
        print("❌ Hücre bulunamadı!")
        return
    
    print("\n✍️ 3/3 PDF'e yazılıyor...")
    applied = apply_translations(input_pdf, data, output_pdf, page_width, page_height, 0)
    
    print(f"\n✅ Tamamlandı! {applied} hücre çevrildi")
    print(f"   Çıktı: {output_pdf}")
    
    # Örnek hücreler
    print("\n📋 Örnek hücreler:")
    for cell in cells[:8]:
        print(f"   [{cell.get('type','?'):8}] {cell.get('text','')[:35]}...")
        print(f"            → {cell.get('translation','')[:35]}...")


if __name__ == "__main__":
    main()

