#!/usr/bin/env python3
"""
DeepL Döküman Çeviri Testi
- TXT dosyasını glossary ile/glossary'siz çevirir
- Farkı gösterir
"""

import requests
import time
import os

# Config
DEEPL_API_KEY = "b121dc7e-8e98-427f-8984-54c4d4f0851e"
DEEPL_API_URL = "https://api.deepl.com/v2"
GLOSSARY_ID = "be996339-a463-4f44-9271-66a93c2565dd"

TEST_CONTENT = """HYDRAULIC SYSTEM MAINTENANCE GUIDE

Chapter 1: Travel Motor Inspection

Before starting any maintenance work on the travel motor, ensure the machine is properly secured and the engine is off.

1. Check the belt tension on all drive components
2. Inspect the undercarriage for wear and damage  
3. Verify the transmission fluid level is within specifications
4. Examine the boom cylinder for oil leakage
5. Test the hydraulic pump pressure at 350 bar

Warning: The fuel filter must be replaced every 500 operating hours. Failure to do so may result in engine damage.

Note: Always refer to the parts catalog for correct part numbers when ordering replacement components.

SPECIFICATIONS:
- Hydraulic pump: 250 bar operating pressure
- Travel motor: 180 rpm maximum speed
- Engine oil capacity: 25 liters
- Fuel tank capacity: 400 liters

For technical support, contact your authorized dealer."""

def translate_document(content, use_glossary=False):
    """Dökümanı çevir"""
    
    # Geçici dosya oluştur
    temp_file = "/tmp/test_doc.txt"
    with open(temp_file, "w", encoding="utf-8") as f:
        f.write(content)
    
    headers = {
        "Authorization": f"DeepL-Auth-Key {DEEPL_API_KEY}"
    }
    
    # 1. Döküman yükle
    data = {
        "target_lang": "TR",
        "source_lang": "EN"
    }
    
    if use_glossary:
        data["glossary_id"] = GLOSSARY_ID
    
    with open(temp_file, "rb") as f:
        files = {"file": ("document.txt", f, "text/plain")}
        response = requests.post(
            f"{DEEPL_API_URL}/document",
            headers=headers,
            data=data,
            files=files
        )
    
    if response.status_code != 200:
        print(f"Upload hatası: {response.status_code}")
        print(response.text)
        return None
    
    result = response.json()
    doc_id = result["document_id"]
    doc_key = result["document_key"]
    
    print(f"   📤 Yüklendi: {doc_id}")
    
    # 2. Durum kontrol (çeviri bitene kadar)
    while True:
        status_resp = requests.post(
            f"{DEEPL_API_URL}/document/{doc_id}",
            headers=headers,
            data={"document_key": doc_key}
        )
        
        status = status_resp.json()
        state = status.get("status")
        
        if state == "done":
            print(f"   ✅ Çeviri tamamlandı")
            break
        elif state == "error":
            print(f"   ❌ Hata: {status.get('message')}")
            return None
        else:
            print(f"   ⏳ Çevriliyor... ({state})")
            time.sleep(1)
    
    # 3. Sonucu indir
    download_resp = requests.post(
        f"{DEEPL_API_URL}/document/{doc_id}/result",
        headers=headers,
        data={"document_key": doc_key}
    )
    
    if download_resp.status_code == 200:
        return download_resp.text
    else:
        print(f"Download hatası: {download_resp.status_code}")
        return None

def compare_translations():
    """Glossary'li ve glossary'siz çeviriyi karşılaştır"""
    
    print("=" * 70)
    print("📄 DEEPL DÖKÜMAN ÇEVİRİ TESTİ")
    print("=" * 70)
    
    print("\n📝 ORİJİNAL İNGİLİZCE METİN:")
    print("-" * 70)
    print(TEST_CONTENT[:500] + "...")
    
    # Glossary'siz çeviri
    print("\n\n❌ GLOSSARY'SİZ ÇEVİRİ:")
    print("-" * 70)
    result_without = translate_document(TEST_CONTENT, use_glossary=False)
    if result_without:
        print(result_without)
    
    # Glossary'li çeviri
    print("\n\n✅ GLOSSARY'Lİ ÇEVİRİ:")
    print("-" * 70)
    result_with = translate_document(TEST_CONTENT, use_glossary=True)
    if result_with:
        print(result_with)
    
    # Farkları göster
    if result_without and result_with:
        print("\n\n🔍 ÖNEMLİ FARKLAR:")
        print("=" * 70)
        
        comparisons = [
            ("travel motor", "Yürüyüş motoru"),
            ("belt", "Kayış"),
            ("undercarriage", "Alt şase"),
            ("boom cylinder", "Bom silindiri"),
        ]
        
        for en_term, expected_tr in comparisons:
            in_without = result_without.lower() if result_without else ""
            in_with = result_with.lower() if result_with else ""
            
            print(f"\n   '{en_term}':")
            if expected_tr.lower() in in_with and expected_tr.lower() not in in_without:
                print(f"      ❌ Glossary'siz: Farklı çeviri")
                print(f"      ✅ Glossary'li: '{expected_tr}' ✓")

def main():
    compare_translations()
    print("\n" + "=" * 70)
    print("✅ TEST TAMAMLANDI")
    print("=" * 70)

if __name__ == "__main__":
    main()

