"""
WRL Dönüştürme Test Script

ERKEK.CATPart dosyasını WRL formatına dönüştürür
"""

import requests
import json
import sys
import io

# Encoding düzelt
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

# Server ayarları
SERVER_URL = "http://localhost:1989"

# Test dosyası - şu anda CATIA'da açık olan dosya
SOURCE_FILE = r"D:\__sistem__\Masaustu\FikatiaV2024\ERKEK.CATPart"
OUTPUT_DIR = r"D:\__sistem__\Masaustu\FikatiaV2024\IDialoglar\IDialogCevirici"
OUTPUT_NAME = "ERKEK_converted"

print("=" * 70)
print("  WRL Dönüştürme Testi")
print("=" * 70)

# Test 1: Health Check
print("\n[1/3] Server sağlık kontrolü...")
print("-" * 70)

try:
    response = requests.get(f"{SERVER_URL}/health", timeout=5)
    if response.status_code == 200:
        print(f"  ✓ Server çalışıyor: {response.text}")
    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  Lütfen önce:")
    print("    1. Dialog penceresini açın (basit_test.py)")
    print("    2. 'Server Başlat' butonuna tıklayın")
    sys.exit(1)

# Test 2: Status
print("\n[2/3] Server durum kontrolü...")
print("-" * 70)

try:
    response = requests.get(f"{SERVER_URL}/status", timeout=5)
    if response.status_code == 200:
        status = response.json()
        print(f"  ✓ Server Durumu:")
        print(f"    - Status: {status.get('status')}")
        print(f"    - Server: {status.get('server')}")
        print(f"    - CATIA: {'✓ Bağlı' if status.get('catia_connected') else '✗ Bağlı değil'}")
    else:
        print(f"  ✗ Status hatası: {response.status_code}")
except Exception as e:
    print(f"  ✗ Hata: {e}")

# Test 3: WRL Dönüştürme
print("\n[3/3] WRL Dönüştürme...")
print("-" * 70)

print(f"  Kaynak: {SOURCE_FILE}")
print(f"  Çıktı: {OUTPUT_DIR}\\{OUTPUT_NAME}.wrl")

try:
    request_data = {
        'source_file': SOURCE_FILE,
        'output_dir': OUTPUT_DIR,
        'output_name': OUTPUT_NAME
    }

    print("\n  İstek gönderiliyor...")
    response = requests.post(
        f"{SERVER_URL}/convert",
        json=request_data,
        timeout=120  # WRL dönüşümü zaman alabilir
    )

    if response.status_code == 200:
        result = response.json()
        print(f"\n  ✓ DÖNÜŞTÜRME BAŞARILI!")
        print(f"    - Çıktı Dosyası: {result.get('output_file')}")
        print(f"    - Timestamp: {result.get('timestamp')}")

        # Dosya var mı kontrol et
        import os
        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")
            print(f"\n  ✓ WRL dosyası başarıyla oluşturuldu!")
        else:
            print(f"\n  ⚠ Uyarı: Çıktı dosyası bulunamadı")

    else:
        print(f"\n  ✗ Dönüştürme hatası: {response.status_code}")
        print(f"  Detay: {response.text}")

except Exception as e:
    print(f"\n  ✗ İstek hatası: {e}")
    import traceback
    traceback.print_exc()

print("\n" + "=" * 70)
print("  Test Tamamlandı")
print("=" * 70)
