#!/usr/bin/env python3
"""
Tritri Test Runner
Runs comprehensive tests for the Tritri expense tracking app
"""

import subprocess
import sys
import time
import requests
import os
from pathlib import Path

def check_backend_health():
    """Check if backend is running"""
    try:
        response = requests.get("http://localhost:8000/", timeout=5)
        return response.status_code == 200
    except:
        return False

def check_frontend_health():
    """Check if frontend is running"""
    try:
        response = requests.get("http://localhost:3002/", timeout=5)
        return response.status_code == 200
    except:
        return False

def run_api_tests():
    """Run API tests"""
    print("\n🧪 Running API Tests...")
    print("=" * 50)

    try:
        result = subprocess.run([
            sys.executable, "tests/test_api.py"
        ], capture_output=True, text=True, cwd=Path(__file__).parent)

        print(result.stdout)
        if result.stderr:
            print("Errors:", result.stderr)

        return result.returncode == 0
    except Exception as e:
        print(f"❌ API tests failed with error: {e}")
        return False

def run_frontend_tests():
    """Run frontend tests with integration test suite"""
    print("\n🎭 Running Frontend & Integration Tests...")
    print("=" * 50)

    try:
        # Run integration tests
        test_result = subprocess.run([
            sys.executable, "test_integration.py"
        ], capture_output=True, text=True, cwd=Path(__file__).parent)

        print(test_result.stdout)
        if test_result.stderr:
            print("Errors:", test_result.stderr)

        return test_result.returncode == 0

    except Exception as e:
        print(f"❌ Frontend tests failed with error: {e}")
        return False

def main():
    """Main test runner"""
    print("🚀 Tritri Test Suite")
    print("=" * 50)

    # Check if Docker containers are running
    print("Checking service health...")

    backend_running = check_backend_health()
    frontend_running = check_frontend_health()

    if not backend_running:
        print("❌ Backend is not running on http://localhost:8000")
        print("Please start the backend with: docker-compose up backend")
        return 1

    if not frontend_running:
        print("❌ Frontend is not running on http://localhost:3002")
        print("Please start the frontend with: docker-compose up frontend")
        return 1

    print("✅ Both services are running!")

    # Run tests
    all_passed = True

    # API tests
    if not run_api_tests():
        all_passed = False

    # Frontend tests
    if not run_frontend_tests():
        all_passed = False

    # Summary
    print("\n" + "=" * 50)
    if all_passed:
        print("🎉 All tests passed!")
        print("\n📋 Test Summary:")
        print("✅ API endpoints working correctly")
        print("✅ Frontend user interface functional")
        print("✅ Multi-trip identity management working")
        print("✅ Trip creation and joining functional")
        print("✅ Navigation and switching between trips working")
        return 0
    else:
        print("❌ Some tests failed!")
        print("Please check the error messages above.")
        return 1

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