#!/usr/bin/env python3
"""
Manual test validation script for Tritri fixes
Tests the key issues that were reported
"""

import requests
import time

def test_api_health():
    """Test that backend API is responding"""
    print("🧪 Testing API Health...")
    try:
        response = requests.get("http://localhost:8000/health", timeout=5)
        if response.status_code == 200:
            print("✅ Backend API is healthy")
            return True
        else:
            print(f"❌ API returned status {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ API connection failed: {e}")
        return False

def test_trip_creation():
    """Test trip creation functionality"""
    print("\n🧪 Testing Trip Creation...")
    try:
        trip_data = {
            "name": "Test Trip for Validation",
            "creator_name": "Validation Test User",
            "currency_code": "USD"
        }

        response = requests.post("http://localhost:8000/api/trips/", json=trip_data, timeout=10)
        if response.status_code == 200:
            trip = response.json()
            print(f"✅ Trip created successfully: {trip['name']} (ID: {trip['id']})")
            return trip
        else:
            print(f"❌ Trip creation failed: {response.status_code}")
            return None
    except Exception as e:
        print(f"❌ Trip creation error: {e}")
        return None

def test_trip_retrieval(trip_id):
    """Test trip retrieval functionality"""
    print(f"\n🧪 Testing Trip Retrieval (ID: {trip_id})...")
    try:
        response = requests.get(f"http://localhost:8000/api/trips/{trip_id}", timeout=10)
        if response.status_code == 200:
            trip = response.json()
            print(f"✅ Trip retrieved successfully: {trip['name']}")
            return True
        else:
            print(f"❌ Trip retrieval failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Trip retrieval error: {e}")
        return False

def test_expense_creation(trip_id):
    """Test expense creation functionality"""
    print(f"\n🧪 Testing Expense Creation (Trip ID: {trip_id})...")
    try:
        # First add a participant
        participant_data = {"name": "Test Participant"}
        participant_response = requests.post(
            f"http://localhost:8000/api/participants/{trip_id}/participants",
            json=participant_data,
            timeout=10
        )

        if participant_response.status_code != 200:
            print(f"❌ Participant creation failed: {participant_response.status_code}")
            return False

        participant = participant_response.json()

        # Now create an expense
        expense_data = {
            "description": "Test Expense",
            "amount": 100.00,
            "currency_code": "USD",
            "exchange_rate": 1.0,
            "category": "Food & Dining",
            "paid_by_id": participant["id"],
            "splits": [
                {"participant_id": participant["id"], "percentage": 100.0}
            ]
        }

        response = requests.post(
            f"http://localhost:8000/api/expenses/{trip_id}/expenses",
            json=expense_data,
            timeout=10
        )

        if response.status_code == 200:
            expense = response.json()
            print(f"✅ Expense created successfully: {expense['description']}")
            return True
        else:
            print(f"❌ Expense creation failed: {response.status_code}")
            print(f"Response: {response.text}")
            return False

    except Exception as e:
        print(f"❌ Expense creation error: {e}")
        return False

def test_currency_conversion():
    """Test currency conversion functionality"""
    print("\n🧪 Testing Currency Conversion...")
    try:
        response = requests.get(
            "http://localhost:8000/api/currency/convert?amount=100&from_currency=USD&to_currency=EUR",
            timeout=10
        )

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Currency conversion working: $100 = €{data['converted_amount']:.2f}")
            return True
        else:
            print(f"❌ Currency conversion failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Currency conversion error: {e}")
        return False

def test_export_functionality(trip_id):
    """Test export functionality"""
    print(f"\n🧪 Testing Export Functionality (Trip ID: {trip_id})...")
    try:
        response = requests.get(
            f"http://localhost:8000/api/export/{trip_id}/expenses/csv",
            timeout=10
        )

        if response.status_code == 200:
            print("✅ Expense export working (CSV format)")
            return True
        else:
            print(f"❌ Export functionality failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Export functionality error: {e}")
        return False

def main():
    """Main test runner"""
    print("🚀 Tritri Manual Validation Tests")
    print("=" * 50)
    print("This script validates that the reported issues have been fixed.\n")

    results = []

    # Test API health
    results.append(("API Health", test_api_health()))

    # Test trip creation
    trip = test_trip_creation()
    if trip:
        trip_id = trip["id"]

        # Test trip retrieval (this tests the "Failed to load trip data" issue)
        results.append(("Trip Retrieval", test_trip_retrieval(trip_id)))

        # Test expense creation
        results.append(("Expense Creation", test_expense_creation(trip_id)))

        # Test export functionality
        results.append(("Export Functionality", test_export_functionality(trip_id)))
    else:
        results.append(("Trip Retrieval", False))
        results.append(("Expense Creation", False))
        results.append(("Export Functionality", False))

    # Test currency conversion
    results.append(("Currency Conversion", test_currency_conversion()))

    # Summary
    print("\n" + "=" * 50)
    print("📋 VALIDATION SUMMARY")
    print("=" * 50)

    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 VALIDATIONS PASSED!")
        print("✅ Backend API is working correctly")
        print("✅ Trip creation and access is working")
        print("✅ Expense tracking is functional")
        print("✅ Currency conversion is working")
        print("✅ Export functionality is working")
        print("\nThe 'Failed to load trip data' issue should be resolved!")
        print("Frontend should now be able to access trips without errors.")
    else:
        print("\n❌ SOME VALIDATIONS FAILED!")
        print("⚠️ Please review the failed tests and fix remaining issues")

    return 0 if all_passed else 1

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