#!/usr/bin/env python3
"""
Integration test for the Smart Vehicle Registration fixes.
Tests: login, catalog filtering, vehicle registration.
"""
import asyncio
import sys
import os
sys.path.insert(0, '/app')

from fastapi.testclient import TestClient
from app.api.v1.api import api_router
from fastapi import FastAPI
from app.core.config import settings
import json

app = FastAPI()
app.include_router(api_router)
client = TestClient(app)

def test_login():
    """Login with tester_pro@profibot.hu and Password123!"""
    print("1. Testing login...")
    response = client.post("/auth/login", json={
        "email": "tester_pro@profibot.hu",
        "password": "Password123!"
    })
    if response.status_code != 200:
        print(f"   ❌ Login failed: {response.status_code} {response.text}")
        return None
    token = response.json().get("access_token")
    print(f"   ✅ Login successful, token: {token[:20]}...")
    return token

def test_catalog_makes(token):
    """Test catalog makes endpoint with auth."""
    print("2. Testing catalog makes...")
    response = client.get("/catalog/makes", headers={"Authorization": f"Bearer {token}"})
    if response.status_code != 200:
        print(f"   ❌ Makes failed: {response.status_code} {response.text}")
        return None
    makes = response.json()
    print(f"   ✅ Makes retrieved: {len(makes)} items")
    return makes

def test_catalog_models_filter(token, make, vehicle_class):
    """Test catalog models endpoint with vehicle_class filter."""
    print(f"3. Testing catalog models with make={make}, vehicle_class={vehicle_class}...")
    params = {"make": make}
    if vehicle_class:
        params["vehicle_class"] = vehicle_class
    response = client.get("/catalog/models", headers={"Authorization": f"Bearer {token}"}, params=params)
    if response.status_code != 200:
        print(f"   ❌ Models failed: {response.status_code} {response.text}")
        return None
    models = response.json()
    print(f"   ✅ Models retrieved: {len(models)} items")
    return models

def test_vehicle_registration(token, org_id=None):
    """Test vehicle registration endpoint with a minimal payload."""
    print("4. Testing vehicle registration...")
    payload = {
        "license_plate": "TEST-123",
        "brand": "Toyota",
        "model": "Corolla",
        "vehicle_class": "passenger_car",
        "fuel_type": "petrol",
        "current_mileage": 50000,
        "status": "draft",
        "organization_id": org_id,
        "owner_org_id": org_id,
        "operator_org_id": org_id,
    }
    response = client.post("/assets/vehicles", 
                          headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
                          json=payload)
    if response.status_code not in (200, 201):
        print(f"   ❌ Registration failed: {response.status_code} {response.text}")
        return None
    result = response.json()
    print(f"   ✅ Vehicle registered: ID {result.get('id')}")
    return result

def main():
    print("=== Integration Test for Smart Vehicle Registration Fixes ===")
    token = test_login()
    if not token:
        print("❌ Test aborted due to login failure.")
        return
    
    makes = test_catalog_makes(token)
    if not makes:
        print("❌ Test aborted due to catalog failure.")
        return
    
    # Test filtering
    test_make = makes[0] if makes else "Toyota"
    models_all = test_catalog_models_filter(token, test_make, None)
    models_car = test_catalog_models_filter(token, test_make, "passenger_car")
    models_motorcycle = test_catalog_models_filter(token, test_make, "motorcycle")
    
    # Compare counts
    if models_all and models_car:
        if len(models_car) <= len(models_all):
            print("   ✅ Filtering works (car count <= all count)")
        else:
            print("   ⚠ Filtering anomaly (car count > all count)")
    
    # Test registration (requires organization ID, but we can try without)
    # First get user's organizations
    print("5. Fetching user organizations...")
    response = client.get("/organizations/my", headers={"Authorization": f"Bearer {token}"})
    if response.status_code == 200:
        orgs = response.json()
        if orgs:
            org_id = orgs[0].get("organization_id")
            print(f"   Using organization ID: {org_id}")
            test_vehicle_registration(token, org_id)
        else:
            print("   No organizations, testing without org...")
            test_vehicle_registration(token, None)
    else:
        print(f"   Could not fetch organizations: {response.status_code}")
        test_vehicle_registration(token, None)
    
    print("=== Integration Test Completed ===")

if __name__ == "__main__":
    main()