"""
WRL Dönüştürme Testi - Port 1989
Normal Mode ve Batch Mode karşılaştırmalı test
"""

import requests
import json
import sys
import io
import os
import time

# Encoding düzelt
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

SERVER_URL = "http://localhost:1989"
SOURCE_FILE = r"D:\__sistem__\Downloads\C0000638.stp"
OUTPUT_DIR = r"D:\__sistem__\Masaustu\FikatiaV2024\IDialoglar\IDialogCevirici"

print("=" * 70)
print("  WRL Dönüştürme Testi - Normal vs Batch Mode")
print("=" * 70)

print(f"\nKaynak Dosya: {SOURCE_FILE}")
print(f"Çıktı Klasörü: {OUTPUT_DIR}")

# Dosya tipini belirle
file_ext = os.path.splitext(SOURCE_FILE)[1].lower()
is_stp = file_ext in ['.stp', '.step']
is_catpart = file_ext == '.catpart'

print(f"Dosya Tipi: {file_ext.upper()}")

# Kaynak dosya var mı?
if not os.path.exists(SOURCE_FILE):
    print(f"\n✗ HATA: Kaynak dosya bulunamadı!")
    print(f"  {SOURCE_FILE}")
    sys.exit(1)

print(f"✓ Kaynak dosya mevcut ({os.path.getsize(SOURCE_FILE):,} bytes)")

# Mod seçimi önerisi
print("\n" + "=" * 70)
print("  MOD ÖNERİSİ")
print("=" * 70)

if is_stp:
    print("\n  📌 STP dosyası tespit edildi")
    print("  ✅ ÖNERİLEN: Batch Mode (/convert_batch)")
    print("  ⚠  Normal Mode STP dosyalarında sorun yaşayabilir")
    recommended_mode = 'batch'
elif is_catpart:
    print("\n  📌 CATPart dosyası tespit edildi")
    print("  ✅ ÖNERİLEN: Normal Mode (/convert)")
    print("  ⚠  Batch Mode daha yavaş olacaktır")
    recommended_mode = 'normal'
else:
    print("\n  📌 Bilinmeyen dosya tipi")
    print("  ⚠  Her iki modu da deneyebilirsiniz")
    recommended_mode = 'both'

print("\n  Hangi modu kullanmak istersiniz?")
print("    1. Normal Mode  (hızlı, mevcut CATIA)")
print("    2. Batch Mode   (yavaş, bağımsız CATIA)")
print("    3. Her İkisi de (karşılaştırma)")
print()

# Kullanıcı seçimi al
mode_choice = input("  Seçiminiz (1/2/3): ").strip()

if mode_choice not in ['1', '2', '3']:
    print("\n✗ Geçersiz seçim!")
    sys.exit(1)

# Server kontrolü
print("\n" + "=" * 70)
print("  SERVER KONTROLÜ")
print("=" * 70)

try:
    response = requests.get(f"{SERVER_URL}/health", timeout=5)
    if response.status_code == 200:
        print("  ✓ Server çalışıyor")
    else:
        print(f"  ✗ Server hatası: {response.status_code}")
        sys.exit(1)
except Exception as e:
    print(f"  ✗ Server'a bağlanılamıyor: {e}")
    print("\n  Dialog penceresinde 'Server Başlat' butonuna tıkladınız mı?")
    sys.exit(1)

# Test fonksiyonları
def test_normal_mode():
    """Normal Mode (/convert) testi"""
    print("\n" + "=" * 70)
    print("  TEST 1: NORMAL MODE (/convert)")
    print("=" * 70)

    output_name = "C0000638_normal"

    print(f"\n  Endpoint: POST /convert")
    print(f"  Çıktı   : {output_name}.wrl")
    print(f"  Method  : Mevcut CATIA oturumu")
    print("\n  İstek gönderiliyor...")

    start_time = time.time()

    try:
        response = requests.post(f"{SERVER_URL}/convert", json={
            'source_file': SOURCE_FILE,
            'output_dir': OUTPUT_DIR,
            'output_name': output_name
        }, timeout=120)

        elapsed_time = time.time() - start_time

        if response.status_code == 200:
            result = response.json()

            print(f"\n  ✓✓✓ BAŞARILI! ✓✓✓")
            print(f"\n  Sonuç:")
            print(f"    - Süre        : {elapsed_time:.2f} saniye")
            print(f"    - Çıktı       : {result.get('output_file')}")
            print(f"    - Timestamp   : {result.get('timestamp')}")

            # Dosya kontrol
            output_file = result.get('output_file')
            if output_file and os.path.exists(output_file):
                file_size = os.path.getsize(output_file)
                print(f"    - Dosya Boyutu: {file_size:,} bytes")
                return True, elapsed_time, file_size
            else:
                print(f"\n  ⚠ Uyarı: Çıktı dosyası bulunamadı")
                return False, elapsed_time, 0
        else:
            print(f"\n  ✗ HATA!")
            print(f"  HTTP Kodu: {response.status_code}")
            print(f"  Yanıt: {response.text}")
            return False, elapsed_time, 0

    except requests.exceptions.Timeout:
        elapsed_time = time.time() - start_time
        print(f"\n  ✗ Timeout hatası! ({elapsed_time:.2f} saniye)")
        return False, elapsed_time, 0

    except Exception as e:
        elapsed_time = time.time() - start_time
        print(f"\n  ✗ İstek hatası: {e}")
        import traceback
        traceback.print_exc()
        return False, elapsed_time, 0


def test_batch_mode():
    """Batch Mode (/convert_batch) testi"""
    print("\n" + "=" * 70)
    print("  TEST 2: BATCH MODE (/convert_batch)")
    print("=" * 70)

    output_name = "C0000638_batch"

    print(f"\n  Endpoint: POST /convert_batch")
    print(f"  Çıktı   : {output_name}.wrl")
    print(f"  Method  : Bağımsız CATIA process")
    print("\n  ⚠ CATIA yeni bir process olarak başlatılacak")
    print("  ⚠ Bu işlem 30-120 saniye sürebilir...")
    print("\n  İstek gönderiliyor...")

    start_time = time.time()

    try:
        response = requests.post(f"{SERVER_URL}/convert_batch", json={
            'source_file': SOURCE_FILE,
            'output_dir': OUTPUT_DIR,
            'output_name': output_name
        }, timeout=180)

        elapsed_time = time.time() - start_time

        if response.status_code == 200:
            result = response.json()

            print(f"\n  ✓✓✓ BAŞARILI! ✓✓✓")
            print(f"\n  Sonuç:")
            print(f"    - Süre        : {elapsed_time:.2f} saniye")
            print(f"    - Method      : {result.get('method', 'batch')}")
            print(f"    - Çıktı       : {result.get('output_file')}")
            print(f"    - Timestamp   : {result.get('timestamp')}")

            # Dosya kontrol
            output_file = result.get('output_file')
            if output_file and os.path.exists(output_file):
                file_size = result.get('file_size', os.path.getsize(output_file))
                print(f"    - Dosya Boyutu: {file_size:,} bytes")
                return True, elapsed_time, file_size
            else:
                print(f"\n  ⚠ Uyarı: Çıktı dosyası bulunamadı")
                return False, elapsed_time, 0
        else:
            print(f"\n  ✗ HATA!")
            print(f"  HTTP Kodu: {response.status_code}")
            print(f"  Yanıt: {response.text}")
            return False, elapsed_time, 0

    except requests.exceptions.Timeout:
        elapsed_time = time.time() - start_time
        print(f"\n  ✗ Timeout hatası! ({elapsed_time:.2f} saniye)")
        print("  CATIA process'i hala çalışıyor olabilir")
        return False, elapsed_time, 0

    except Exception as e:
        elapsed_time = time.time() - start_time
        print(f"\n  ✗ İstek hatası: {e}")
        import traceback
        traceback.print_exc()
        return False, elapsed_time, 0


# Testleri çalıştır
results = {}

if mode_choice in ['1', '3']:
    success, time_taken, size = test_normal_mode()
    results['normal'] = {'success': success, 'time': time_taken, 'size': size}

if mode_choice in ['2', '3']:
    if mode_choice == '3':
        print("\n  (5 saniye bekleniyor...)")
        time.sleep(5)
    success, time_taken, size = test_batch_mode()
    results['batch'] = {'success': success, 'time': time_taken, 'size': size}


# Karşılaştırmalı sonuçlar
if mode_choice == '3' and len(results) == 2:
    print("\n" + "=" * 70)
    print("  KARŞILAŞTIRMA")
    print("=" * 70)

    print("\n  ┌─────────────┬──────────────┬──────────────┐")
    print("  │  Özellik    │ Normal Mode  │  Batch Mode  │")
    print("  ├─────────────┼──────────────┼──────────────┤")

    # Süre karşılaştırma
    normal_time = results['normal']['time']
    batch_time = results['batch']['time']
    print(f"  │  Süre       │  {normal_time:>9.2f}s  │  {batch_time:>9.2f}s  │")

    # Başarı durumu
    normal_status = "✓ Başarılı" if results['normal']['success'] else "✗ Başarısız"
    batch_status = "✓ Başarılı" if results['batch']['success'] else "✗ Başarısız"
    print(f"  │  Durum      │  {normal_status:<10} │  {batch_status:<10} │")

    # Dosya boyutu
    if results['normal']['size'] > 0 and results['batch']['size'] > 0:
        normal_mb = results['normal']['size'] / 1024 / 1024
        batch_mb = results['batch']['size'] / 1024 / 1024
        print(f"  │  Boyut      │  {normal_mb:>7.2f} MB  │  {batch_mb:>7.2f} MB  │")

    print("  └─────────────┴──────────────┴──────────────┘")

    # Hız farkı
    if results['normal']['success'] and results['batch']['success']:
        speed_diff = batch_time - normal_time
        if speed_diff > 0:
            print(f"\n  📊 Normal Mode {speed_diff:.2f} saniye daha hızlı")
        else:
            print(f"\n  📊 Batch Mode {abs(speed_diff):.2f} saniye daha hızlı")


# Test özeti
print("\n" + "=" * 70)
print("  TEST TAMAMLANDI")
print("=" * 70)

success_count = sum(1 for r in results.values() if r['success'])
total_tests = len(results)

print(f"\n  Toplam Test  : {total_tests}")
print(f"  Başarılı     : {success_count}")
print(f"  Başarısız    : {total_tests - success_count}")

# İpuçları
print("\n💡 İpuçları:")
print("   - Dialog penceresindeki log alanını kontrol edin")
print("   - STP dosyaları için Batch Mode önerilir")
print("   - CATPart dosyaları için Normal Mode daha hızlıdır")

if is_stp and 'normal' in results and not results['normal']['success']:
    print("\n⚠️  STP dosyası Normal Mode'da başarısız oldu")
    print("   Batch Mode kullanmanız önerilir:")
    print("   python test_batch_mode.py")

print()
