#!/usr/bin/env python3
"""
Simple test to verify catalog endpoints work with authentication.
"""
import http.client
import json
import urllib.parse

def test_catalog_with_auth():
    """Test catalog endpoints with authentication."""
    conn = http.client.HTTPConnection("localhost", 8000)
    
    # Try multiple test users
    test_users = [
        ("test@profibot.hu", "test123"),
        ("admin@profibot.hu", "Kincs€s74"),  # From .env INITIAL_ADMIN_PASSWORD
        ("superadmin@profibot.hu", "Kincs€s74"),
    ]
    
    access_token = None
    user_email = None
    
    for email, password in test_users:
        print(f"Trying login with {email}...")
        login_data = urllib.parse.urlencode({
            "username": email,
            "password": password
        })
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }
        
        try:
            conn.request("POST", "/api/v1/auth/login", login_data, headers)
            response = conn.getresponse()
            data = response.read()
            
            if response.status == 200:
                token_data = json.loads(data.decode())
                access_token = token_data.get("access_token")
                if access_token:
                    user_email = email
                    print(f"Login successful with {email}")
                    break
                else:
                    print(f"No access token in response for {email}")
            else:
                print(f"Login failed for {email}: {response.status} {response.reason}")
                # Try next user
                continue
                
        except Exception as e:
            print(f"Error during login for {email}: {e}")
            continue
    
    if not access_token:
        print("All login attempts failed")
        return False
    
    # Test catalog makes endpoint
    print(f"\nTesting catalog makes endpoint with {user_email}...")
    auth_headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json"
    }
    
    try:
        conn.request("GET", "/api/v1/catalog/makes", headers=auth_headers)
        response = conn.getresponse()
        data = response.read()
        
        if response.status != 200:
            print(f"Makes endpoint failed: {response.status} {response.reason}")
            print(f"Response: {data.decode()}")
            return False
        
        makes = json.loads(data.decode())
        print(f"Success! Retrieved {len(makes)} makes")
        
        # Show all makes
        print("\nAll makes:")
        for i, make in enumerate(makes[:20], 1):
            print(f"  {i}. {make}")
        if len(makes) > 20:
            print(f"  ... and {len(makes) - 20} more")
        
        # Count normal makes (alphabetic)
        normal_makes = [m for m in makes if isinstance(m, str) and m.isalpha()]
        print(f"\nNormal makes (alphabetic): {len(normal_makes)}")
        
        if len(normal_makes) >= 5:
            print(f"✓ SUCCESS: Found at least 5 normal makes")
            print(f"Sample normal makes: {normal_makes[:10]}")
            
            # Test models endpoint with first normal make
            if normal_makes:
                test_make = normal_makes[0]
                print(f"\nTesting models endpoint for make '{test_make}'...")
                conn.request("GET", f"/api/v1/catalog/models?make={test_make}", headers=auth_headers)
                response = conn.getresponse()
                data = response.read()
                
                if response.status == 200:
                    models = json.loads(data.decode())
                    print(f"Success! Retrieved {len(models)} models for {test_make}")
                    if models:
                        print(f"Sample models: {models[:5]}")
                else:
                    print(f"Models endpoint failed: {response.status} {response.reason}")
            
            return True
        else:
            print(f"✗ FAILED: Only found {len(normal_makes)} normal makes (need at least 5)")
            return False
            
    except Exception as e:
        print(f"Error during catalog test: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        conn.close()

if __name__ == "__main__":
    print("=== Simple Catalog API Test ===\n")
    success = test_catalog_with_auth()
    print("\n" + "="*50)
    if success:
        print("✓ TEST PASSED: Catalog endpoints working correctly")
        exit(0)
    else:
        print("✗ TEST FAILED")
        exit(1)