"""
IDialogCevirici HTTP Client Test

Bu script IDialogCevirici server'ına HTTP istekleri gönderir.
Server'ın çalışıyor olması gerekir.
"""

import requests
import json
import sys
import os


def test_health_check(base_url="http://localhost:8080"):
    """Server health check testi"""
    print("\n" + "=" * 60)
    print("1. Health Check Testi")
    print("=" * 60)

    try:
        response = requests.get(f"{base_url}/health", timeout=5)

        if response.status_code == 200:
            print(f"✓ Server sağlıklı çalışıyor: {response.text}")
            return True
        else:
            print(f"✗ Beklenmeyen yanıt: {response.status_code}")
            return False

    except requests.exceptions.RequestException as e:
        print(f"✗ Bağlantı hatası: {e}")
        print(f"  Server çalışıyor mu? ({base_url})")
        return False


def test_status(base_url="http://localhost:8080"):
    """Server status testi"""
    print("\n" + "=" * 60)
    print("2. Status Testi")
    print("=" * 60)

    try:
        response = requests.get(f"{base_url}/status", timeout=5)

        if response.status_code == 200:
            status = response.json()
            print("✓ Server durumu:")
            print(f"  - Status: {status.get('status')}")
            print(f"  - Server: {status.get('server')}")
            print(f"  - Version: {status.get('version')}")
            print(f"  - Timestamp: {status.get('timestamp')}")
            print(f"  - CATIA Connected: {status.get('catia_connected')}")
            return True
        else:
            print(f"✗ Beklenmeyen yanıt: {response.status_code}")
            return False

    except requests.exceptions.RequestException as e:
        print(f"✗ Bağlantı hatası: {e}")
        return False


def test_convert(source_file, output_dir=None, output_name="test_converted", base_url="http://localhost:8080"):
    """Dosya dönüştürme testi"""
    print("\n" + "=" * 60)
    print("3. Dosya Dönüştürme Testi")
    print("=" * 60)

    # Kaynak dosya kontrolü
    if not os.path.exists(source_file):
        print(f"✗ Kaynak dosya bulunamadı: {source_file}")
        return False

    # Çıktı klasörü varsayılan
    if output_dir is None:
        output_dir = os.path.dirname(source_file)

    print(f"Kaynak Dosya: {source_file}")
    print(f"Çıktı Klasörü: {output_dir}")
    print(f"Çıktı Adı: {output_name}.wrl")

    try:
        # İstek gövdesini hazırla
        request_data = {
            'source_file': source_file,
            'output_dir': output_dir,
            'output_name': output_name
        }

        # POST isteği gönder
        response = requests.post(
            f"{base_url}/convert",
            json=request_data,
            timeout=60  # WRL dönüşümü zaman alabilir
        )

        if response.status_code == 200:
            result = response.json()
            print("✓ Dönüştürme başarılı!")
            print(f"  - Çıktı Dosyası: {result.get('output_file')}")
            print(f"  - Timestamp: {result.get('timestamp')}")

            # Dosya oluşturuldu mu kontrol et
            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
            else:
                print(f"  ⚠ Çıktı dosyası bulunamadı: {output_file}")
                return False

        else:
            print(f"✗ Dönüştürme hatası: {response.status_code}")
            print(f"  {response.text}")
            return False

    except requests.exceptions.RequestException as e:
        print(f"✗ İstek hatası: {e}")
        return False


def main():
    """Ana test fonksiyonu"""
    print("\n")
    print("╔" + "=" * 58 + "╗")
    print("║  IDialogCevirici HTTP Client Test                       ║")
    print("╚" + "=" * 58 + "╝")

    # Server URL
    base_url = "http://localhost:8080"
    print(f"\nServer URL: {base_url}")

    # Test 1: Health Check
    health_ok = test_health_check(base_url)

    if not health_ok:
        print("\n✗ Server'a bağlanılamadı. Testler durduruluyor.")
        print("\nÖnce IDialogCevirici'yi başlatın ve 'Server Başlat' butonuna tıklayın.")
        return

    # Test 2: Status
    status_ok = test_status(base_url)

    # Test 3: Dosya Dönüştürme (örnek dosya yolu belirtin)
    print("\n" + "=" * 60)
    print("Dosya dönüştürme testi için:")
    print("  python test_client.py <catia_dosyasi.CATPart>")
    print("=" * 60)

    if len(sys.argv) > 1:
        source_file = sys.argv[1]
        convert_ok = test_convert(source_file, base_url=base_url)
    else:
        print("\n⚠ Kaynak dosya belirtilmedi, dönüştürme testi atlanıyor.")
        convert_ok = None

    # Sonuçlar
    print("\n" + "=" * 60)
    print("Test Sonuçları:")
    print("=" * 60)
    print(f"  Health Check: {'✓ Başarılı' if health_ok else '✗ Başarısız'}")
    print(f"  Status Check: {'✓ Başarılı' if status_ok else '✗ Başarısız'}")
    if convert_ok is not None:
        print(f"  File Convert: {'✓ Başarılı' if convert_ok else '✗ Başarısız'}")
    else:
        print(f"  File Convert: - Atlandı")
    print("=" * 60)


if __name__ == '__main__':
    main()
