#!/usr/bin/env python3
"""
Translation Test Script

Tests the GemmaTranslate service end-to-end with monitoring and progress tracking.

Usage:
    python test_translation.py

Requirements:
    - Modal account and token configured (modal token set --token-id XXX --token-secret YYY)
    - modal CLI installed (pip install modal)
"""

import modal
import time
import sys
from datetime import datetime

# Enable Modal build output for debugging
modal.enable_output()

# Test configuration
TEST_TEXT = """
The quick brown fox jumps over the lazy dog. This is a simple test to verify
that our translation system works correctly with a twenty word sentence example.
"""

SOURCE_LANG = "en"
TARGET_LANG = "he"  # Hebrew
TONE = "neutral"


def print_header(text: str):
    """Print formatted header"""
    print(f"\n{'='*70}")
    print(f"  {text}")
    print(f"{'='*70}\n")


def print_step(step: int, text: str):
    """Print test step"""
    print(f"[Step {step}] {text}")


def print_success(text: str):
    """Print success message"""
    print(f"✅ {text}")


def print_error(text: str):
    """Print error message"""
    print(f"❌ {text}")


def print_info(key: str, value: str):
    """Print key-value info"""
    print(f"   {key}: {value}")


def run_test():
    """
    Run comprehensive translation test with monitoring
    """
    print_header("GemmaTranslate Service Test")

    # Test parameters
    print("📋 Test Configuration:")
    print_info("Text", TEST_TEXT.strip()[:100] + "...")
    print_info("Word count", str(len(TEST_TEXT.split())))
    print_info("Character count", str(len(TEST_TEXT)))
    print_info("Source language", SOURCE_LANG)
    print_info("Target language", TARGET_LANG)
    print_info("Tone", TONE)
    print_info("Timestamp", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    try:
        # Import the Modal app (test-only version to avoid FastAPI dependency)
        print_step(1, "Loading Modal app...")
        from gemmatranslate_test_only import app, translate_gemma

        print_success("Modal app loaded")

        # Skip cache check for now (requires web endpoint with FastAPI)
        print_step(2, "Skipping cache check...")
        print("   ⚠️  First run will download ~10GB model (5-10 minutes)")
        print("   ⚠️  Subsequent runs will load from cache (1-2 seconds)")

        # Run translation
        print_step(3, "Starting translation...")
        print("   This may take longer on first run (downloading model)")

        translation_start = time.time()

        with app.run():
            result = translate_gemma.remote(
                TEST_TEXT.strip(),
                SOURCE_LANG,
                TARGET_LANG,
                TONE
            )

        translation_time = time.time() - translation_start

        print_success(f"Translation completed in {translation_time:.2f}s")

        # Display results
        print_header("Translation Results")

        print("📝 Original Text:")
        print(f"   {TEST_TEXT.strip()}\n")

        print("🌐 Translated Text:")
        print(f"   {result['translation']}\n")

        print("📊 Metrics:")
        print_info("Tokens used", str(result['tokens_used']))
        print_info("Processing time (server)", f"{result['processing_time_ms']}ms")
        print_info("Total time (with network)", f"{translation_time*1000:.0f}ms")
        print_info("Model", result['model'])
        print_info("Source language", result['source_lang'])
        print_info("Target language", result['target_lang'])

        # Calculate cost estimate (example pricing)
        tokens = result['tokens_used']
        cost_per_1k = 0.001  # Example: $0.001 per 1K tokens
        estimated_cost = (tokens / 1000) * cost_per_1k

        print(f"\n💰 Estimated Cost:")
        print_info("Tokens", str(tokens))
        print_info("Rate", f"${cost_per_1k} per 1K tokens")
        print_info("Estimated cost", f"${estimated_cost:.6f}")

        # Verify translation is not empty
        print_step(4, "Validating translation...")

        if not result['translation']:
            print_error("Translation is empty")
            return False

        if result['translation'] == TEST_TEXT.strip():
            print_error("Translation is identical to source (may not have translated)")
            return False

        if result['tokens_used'] == 0:
            print_error("No tokens were used")
            return False

        print_success("Translation validation passed")

        # Final success
        print_header("Test Completed Successfully! ✅")

        return True

    except Exception as e:
        print_error(f"Test failed: {str(e)}")
        import traceback
        print("\n📋 Full error trace:")
        traceback.print_exc()
        return False


def test_web_endpoint():
    """
    Test the web endpoint (requires deployed service)
    """
    print_header("Testing Web Endpoint")

    print("⚠️  This test requires the Modal app to be deployed")
    print("   Run: modal deploy gemmatranslate_service.py")
    print("\n   Then update this script with the endpoint URL\n")

    # Example web endpoint test (uncomment and update URL after deployment)
    """
    import requests

    endpoint_url = "https://your-app-name--translate.modal.run"

    request_data = {
        "content": TEST_TEXT.strip(),
        "source_lang": SOURCE_LANG,
        "target_lang": TARGET_LANG,
        "tone": TONE
    }

    print(f"Calling endpoint: {endpoint_url}")

    response = requests.post(endpoint_url, json=request_data, timeout=60)

    if response.status_code == 200:
        result = response.json()
        print_success("Web endpoint test passed")
        print(f"Translation: {result['translation']}")
    else:
        print_error(f"Web endpoint failed: {response.status_code}")
        print(response.text)
    """


if __name__ == "__main__":
    print("\n🚀 Starting GemmaTranslate Translation Test\n")

    success = run_test()

    if success:
        print("\n" + "="*70)
        print("  All tests passed! The translation service is working correctly.")
        print("="*70 + "\n")
        sys.exit(0)
    else:
        print("\n" + "="*70)
        print("  ❌ Tests failed. Please check the errors above.")
        print("="*70 + "\n")
        sys.exit(1)
