#!/usr/bin/env python3
"""
Script de test simple pour l'API DonShare
"""
import requests
import json

BASE_URL = "http://localhost:8000/api/v1"

def test_health():
    """Test de santé de l'API"""
    try:
        response = requests.get("http://localhost:8000/health")
        print(f"✅ Health check: {response.status_code}")
        print(f"   Response: {response.json()}")
        return True
    except Exception as e:
        print(f"❌ Health check failed: {e}")
        return False

def test_register():
    """Test d'inscription d'un utilisateur"""
    try:
        user_data = {
            "email": "test@example.com",
            "username": "testuser",
            "full_name": "Test User",
            "password": "testpassword123"
        }
        response = requests.post(f"{BASE_URL}/auth/register", json=user_data)
        print(f"✅ Register: {response.status_code}")
        if response.status_code == 200:
            print(f"   User created: {response.json()['username']}")
        else:
            print(f"   Error: {response.json()}")
        return response.status_code in [200, 400]  # 400 si l'utilisateur existe déjà
    except Exception as e:
        print(f"❌ Register failed: {e}")
        return False

def test_login():
    """Test de connexion"""
    try:
        login_data = {
            "username": "test@example.com",
            "password": "testpassword123"
        }
        response = requests.post(f"{BASE_URL}/auth/login", data=login_data)
        print(f"✅ Login: {response.status_code}")
        if response.status_code == 200:
            token = response.json()["access_token"]
            print(f"   Token received: {token[:20]}...")
            return token
        else:
            print(f"   Error: {response.json()}")
            return None
    except Exception as e:
        print(f"❌ Login failed: {e}")
        return None

def test_donations(token=None):
    """Test des endpoints de dons"""
    try:
        headers = {}
        if token:
            headers["Authorization"] = f"Bearer {token}"
        
        # Test GET donations
        response = requests.get(f"{BASE_URL}/donations", headers=headers)
        print(f"✅ Get donations: {response.status_code}")
        if response.status_code == 200:
            data = response.json()
            print(f"   Found {len(data['data'])} donations")
        
        # Test GET categories
        response = requests.get(f"{BASE_URL}/categories", headers=headers)
        print(f"✅ Get categories: {response.status_code}")
        if response.status_code == 200:
            categories = response.json()
            print(f"   Found {len(categories)} categories")
        
        return True
    except Exception as e:
        print(f"❌ Donations test failed: {e}")
        return False

def test_site_config():
    """Test de la configuration du site"""
    try:
        response = requests.get(f"{BASE_URL}/site-config/public")
        print(f"✅ Site config: {response.status_code}")
        if response.status_code == 200:
            config = response.json()
            print(f"   Public configs: {len(config)} items")
        return True
    except Exception as e:
        print(f"❌ Site config test failed: {e}")
        return False

def main():
    """Fonction principale de test"""
    print("🚀 Testing DonShare API...")
    print("=" * 50)
    
    # Test de santé
    if not test_health():
        print("❌ API not running. Please start the server first.")
        return
    
    print()
    
    # Test d'inscription
    test_register()
    print()
    
    # Test de connexion
    token = test_login()
    print()
    
    # Test des dons
    test_donations(token)
    print()
    
    # Test de la configuration
    test_site_config()
    print()
    
    print("✅ All tests completed!")

if __name__ == "__main__":
    main()
