#!/usr/bin/env python3
"""
Demo test to show the test infrastructure is working
This test runs without requiring the API server
"""

import sys
import subprocess
import os
from pathlib import Path

def run_backend_unit_tests():
    """Run backend unit tests that don't require API server"""
    print("🧪 Running Backend Unit Tests (Demo)")
    print("=" * 50)

    backend_dir = Path("backend")
    if not backend_dir.exists():
        print("❌ Backend directory not found")
        return False

    # Test currency service without API calls
    try:
        # Change to backend directory
        os.chdir(backend_dir)

        # Add current directory to Python path
        sys.path.insert(0, '.')

        # Import and test currency service directly
        from app.services.currency_service import CurrencyService

        currency_service = CurrencyService()

        # Test same currency conversion
        result = currency_service.get_exchange_rate("USD", "USD")
        assert result == 1.0, f"Expected 1.0, got {result}"
        print("✅ Same currency conversion test passed")

        # Test currency formatting
        formatted = currency_service.format_currency(123.45, "USD")
        assert formatted == "$123.45", f"Expected '$123.45', got '{formatted}'"
        print("✅ Currency formatting test passed")

        # Test JPY formatting (no decimals)
        formatted_jpy = currency_service.format_currency(1234, "JPY")
        assert formatted_jpy == "¥1234", f"Expected '¥1234', got '{formatted_jpy}'"
        print("✅ JPY formatting test passed")

        # Test supported currencies
        currencies = currency_service.get_supported_currencies()
        assert "USD" in currencies, "USD should be in supported currencies"
        assert currencies["USD"] == "US Dollar", "USD should map to US Dollar"
        print("✅ Supported currencies test passed")

        # Test fallback rates
        rate = currency_service.get_exchange_rate("USD", "EUR")
        expected = currency_service.fallback_rates["USD"] / currency_service.fallback_rates["EUR"]
        assert abs(rate - expected) < 0.01, f"Expected ~{expected}, got {rate}"
        print("✅ Fallback rates test passed")

        print("\n🎉 All backend unit tests passed!")
        return True

    except Exception as e:
        print(f"❌ Backend unit test failed: {e}")
        return False
    finally:
        # Go back to original directory
        os.chdir("..")

def test_file_structure():
    """Test that all required test files exist"""
    print("\n🧪 Testing File Structure")
    print("=" * 50)

    required_files = [
        "backend/tests/test_expenses.py",
        "backend/tests/test_currency.py",
        "backend/tests/test_export.py",
        "backend/pytest.ini",
        "backend/requirements.txt",
        "frontend/tests/test_frontend.spec.ts",
        "frontend/tests/test_expenses.spec.ts",
        "frontend/package.json",
        "run_all_tests.py",
        "TEST_DOCUMENTATION.md"
    ]

    missing_files = []
    for file_path in required_files:
        if Path(file_path).exists():
            print(f"✅ {file_path}")
        else:
            print(f"❌ {file_path}")
            missing_files.append(file_path)

    if missing_files:
        print(f"\n❌ Missing {len(missing_files)} files")
        return False
    else:
        print(f"\n✅ All {len(required_files)} required files present")
        return True

def test_frontend_dependencies():
    """Test that frontend dependencies are properly configured"""
    print("\n🧪 Testing Frontend Dependencies")
    print("=" * 50)

    frontend_dir = Path("frontend")
    if not frontend_dir.exists():
        print("❌ Frontend directory not found")
        return False

    # Check package.json
    package_json = frontend_dir / "package.json"
    if package_json.exists():
        print("✅ package.json exists")

        # Check for Playwright
        with open(package_json, 'r') as f:
            content = f.read()
            if "@playwright/test" in content:
                print("✅ Playwright is configured")
            else:
                print("❌ Playwright not found in package.json")
                return False
    else:
        print("❌ package.json not found")
        return False

    # Check test directory
    test_dir = frontend_dir / "tests"
    if test_dir.exists():
        print("✅ Test directory exists")

        test_files = list(test_dir.glob("*.spec.ts"))
        print(f"✅ Found {len(test_files)} test files")
    else:
        print("❌ Test directory not found")
        return False

    return True

def test_backend_dependencies():
    """Test that backend dependencies are properly configured"""
    print("\n🧪 Testing Backend Dependencies")
    print("=" * 50)

    backend_dir = Path("backend")
    if not backend_dir.exists():
        print("❌ Backend directory not found")
        return False

    # Check requirements.txt
    requirements = backend_dir / "requirements.txt"
    if requirements.exists():
        print("✅ requirements.txt exists")

        with open(requirements, 'r') as f:
            content = f.read()

        required_packages = ["pytest", "fastapi", "sqlalchemy"]
        for package in required_packages:
            if package in content:
                print(f"✅ {package} found in requirements")
            else:
                print(f"❌ {package} not found in requirements")
                return False
    else:
        print("❌ requirements.txt not found")
        return False

    # Check pytest.ini
    pytest_ini = backend_dir / "pytest.ini"
    if pytest_ini.exists():
        print("✅ pytest.ini exists")
    else:
        print("❌ pytest.ini not found")
        return False

    # Check test directory
    test_dir = backend_dir / "tests"
    if test_dir.exists():
        print("✅ Test directory exists")

        test_files = list(test_dir.glob("test_*.py"))
        print(f"✅ Found {len(test_files)} test files")
    else:
        print("❌ Test directory not found")
        return False

    return True

def demonstrate_test_categories():
    """Demonstrate the different categories of tests we've created"""
    print("\n🧪 Test Categories Demonstration")
    print("=" * 50)

    categories = {
        "Backend Unit Tests": [
            "Currency service tests (without API calls)",
            "Exchange rate calculation tests",
            "Currency formatting tests",
            "Fallback mechanism tests"
        ],
        "Backend API Tests": [
            "Expense creation and validation",
            "Trip management endpoints",
            "Currency conversion API",
            "Export functionality API",
            "Participant management"
        ],
        "Frontend Component Tests": [
            "Expense modal interactions",
            "Share button functionality",
            "Export button functionality",
            "Form validation",
            "Navigation tests"
        ],
        "Frontend E2E Tests": [
            "Complete user journeys",
            "Multi-trip identity management",
            "Responsive design testing",
            "Cross-browser compatibility"
        ],
        "Integration Tests": [
            "API integration with frontend",
            "Data flow validation",
            "Multi-component interactions",
            "System behavior verification"
        ]
    }

    for category, tests in categories.items():
        print(f"\n📋 {category}:")
        for test in tests:
            print(f"   • {test}")

    total_tests = sum(len(tests) for tests in categories.values())
    print(f"\n✅ Total test categories: {len(categories)}")
    print(f"✅ Total test types covered: {total_tests}")

def main():
    """Main demo function"""
    print("🚀 Tritri Test Infrastructure Demo")
    print("=" * 60)
    print("This demo verifies that our comprehensive test suite is properly set up")
    print("without requiring the full application to be running.\n")

    results = []

    # Test file structure
    results.append(("File Structure", test_file_structure()))

    # Test dependencies
    results.append(("Backend Dependencies", test_backend_dependencies()))
    results.append(("Frontend Dependencies", test_frontend_dependencies()))

    # Test basic functionality
    results.append(("Backend Unit Tests", run_backend_unit_tests()))

    # Demonstrate categories
    demonstrate_test_categories()

    # Summary
    print("\n" + "=" * 60)
    print("📋 DEMO SUMMARY")
    print("=" * 60)

    all_passed = True
    for test_name, passed in results:
        status = "✅ PASSED" if passed else "❌ FAILED"
        print(f"{test_name:<25}: {status}")
        if not passed:
            all_passed = False

    if all_passed:
        print("\n🎉 ALL DEMO TESTS PASSED!")
        print("✅ Test infrastructure is properly configured")
        print("✅ Ready to run comprehensive test suite with:")
        print("   • python run_all_tests.py (when API server is running)")
        print("   • Individual test suites as documented in TEST_DOCUMENTATION.md")
    else:
        print("\n❌ SOME DEMO TESTS FAILED!")
        print("⚠️ Please review and fix configuration issues")
        return 1

    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)