#!/usr/bin/env python3
"""
Test the assets API endpoint directly.
"""
import asyncio
import aiohttp
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

async def test_assets_api():
    base_url = "http://sf_api:8000"
    
    # First, login to get token
    async with aiohttp.ClientSession() as session:
        # Login
        login_data = {
            "username": "tester_pro@profibot.hu",
            "password": "Test123!"
        }
        
        print("1. Logging in...")
        async with session.post(f"{base_url}/api/v1/auth/login", data=login_data) as resp:
            if resp.status != 200:
                print(f"❌ Login failed: {resp.status}")
                text = await resp.text()
                print(f"Response: {text}")
                return
            login_result = await resp.json()
            token = login_result["access_token"]
            print(f"✅ Login successful, token: {token[:50]}...")
        
        # Set personal mode (scope_id = null)
        print("\n2. Setting personal mode (scope_id = null)...")
        headers = {"Authorization": f"Bearer {token}"}
        patch_data = {"organization_id": None}
        
        async with session.patch(
            f"{base_url}/api/v1/users/me/active-organization",
            json=patch_data,
            headers=headers
        ) as resp:
            if resp.status != 200:
                print(f"❌ PATCH failed: {resp.status}")
                text = await resp.text()
                print(f"Response: {text}")
                return
            patch_result = await resp.json()
            print(f"✅ PATCH successful")
            print(f"   scope_id: {patch_result.get('scope_id')}")
            print(f"   scope_level: {patch_result.get('scope_level')}")
        
        # Get vehicles in personal mode
        print("\n3. Getting vehicles in personal mode...")
        async with session.get(
            f"{base_url}/api/v1/assets/vehicles",
            headers=headers
        ) as resp:
            if resp.status != 200:
                print(f"❌ GET vehicles failed: {resp.status}")
                text = await resp.text()
                print(f"Response: {text}")
                return
            vehicles_result = await resp.json()
            print(f"✅ GET vehicles successful")
            print(f"   Found {len(vehicles_result)} vehicles")
            for i, vehicle in enumerate(vehicles_result[:5]):  # Show first 5
                print(f"   {i+1}. {vehicle.get('license_plate')} (ID: {vehicle.get('id')})")
            if len(vehicles_result) > 5:
                print(f"   ... and {len(vehicles_result) - 5} more")
        
        # Now test corporate mode (org_id = 15)
        print("\n4. Setting corporate mode (org_id = 15)...")
        patch_data_corp = {"organization_id": "15"}
        
        async with session.patch(
            f"{base_url}/api/v1/users/me/active-organization",
            json=patch_data_corp,
            headers=headers
        ) as resp:
            if resp.status != 200:
                print(f"❌ PATCH corporate failed: {resp.status}")
                text = await resp.text()
                print(f"Response: {text}")
                return
            patch_corp_result = await resp.json()
            print(f"✅ PATCH corporate successful")
            print(f"   scope_id: {patch_corp_result.get('scope_id')}")
        
        # Get vehicles in corporate mode
        print("\n5. Getting vehicles in corporate mode...")
        async with session.get(
            f"{base_url}/api/v1/assets/vehicles",
            headers=headers
        ) as resp:
            if resp.status != 200:
                print(f"❌ GET corporate vehicles failed: {resp.status}")
                text = await resp.text()
                print(f"Response: {text}")
                return
            vehicles_corp_result = await resp.json()
            print(f"✅ GET corporate vehicles successful")
            print(f"   Found {len(vehicles_corp_result)} vehicles")
            for i, vehicle in enumerate(vehicles_corp_result[:5]):
                print(f"   {i+1}. {vehicle.get('license_plate')}")

if __name__ == "__main__":
    asyncio.run(test_assets_api())