#!/usr/bin/env python3
"""
Test script to verify login and catalog listing for Ticket #142.
Uses built-in http.client to avoid dependency issues.
"""
import http.client
import json
import sys
import urllib.parse

def test_login_and_catalog():
    """Test login and catalog endpoints."""
    conn = http.client.HTTPConnection("localhost", 8000)
    
    # 1. Login to get token (using form-urlencoded data)
    print("1. Logging in as tester_pro@profibot.hu...")
    login_data = urllib.parse.urlencode({
        "username": "tester_pro@profibot.hu",
        "password": "test123"
    })
    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:
            print(f"Login failed: {response.status} {response.reason}")
            print(f"Response: {data.decode()}")
            return False
        
        token_data = json.loads(data.decode())
        access_token = token_data.get("access_token")
        if not access_token:
            print("No access token in response")
            return False
        
        print(f"Login successful, token obtained")
        
        # 2. Test catalog makes endpoint
        print("\n2. Testing catalog makes endpoint...")
        auth_headers = {
            "Authorization": f"Bearer {access_token}",
            "Accept": "application/json"
        }
        
        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")
        
        # Filter out non-standard makes (numeric codes)
        normal_makes = [m for m in makes if isinstance(m, str) and m.isalpha()]
        print(f"Normal makes (alphabetic): {len(normal_makes)}")
        
        if len(normal_makes) >= 5:
            print(f"\n✓ SUCCESS: Found at least 5 normal makes:")
            for i, make in enumerate(normal_makes[:10], 1):
                print(f"  {i}. {make}")
            if len(normal_makes) > 10:
                print(f"  ... and {len(normal_makes) - 10} more")
            
            # 3. Test models endpoint with first normal make
            if normal_makes:
                test_make = normal_makes[0]
                print(f"\n3. Testing 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"\n✗ FAILED: Only found {len(normal_makes)} normal makes (need at least 5)")
            print(f"All makes: {makes}")
            return False
            
    except Exception as e:
        print(f"Error during test: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        conn.close()

if __name__ == "__main__":
    print("=== Catalog API Verification Test ===\n")
    success = test_login_and_catalog()
    print("\n" + "="*50)
    if success:
        print("✓ VERIFICATION PASSED: Login and catalog listing working correctly")
        sys.exit(0)
    else:
        print("✗ VERIFICATION FAILED")
        sys.exit(1)