#!/usr/bin/env python3
"""
Diagnostic script to understand why vehicle filtering isn't working correctly.
"""
import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from sqlalchemy import select, or_
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import AsyncSessionLocal
from app.models.vehicle.asset import Asset
from app.models.identity.identity import User

async def diagnose():
    async with AsyncSessionLocal() as db:
        # Get User 28
        user_stmt = select(User).where(User.id == 28)
        user_result = await db.execute(user_stmt)
        test_user = user_result.scalar_one_or_none()
        
        if not test_user:
            print("❌ User 28 not found")
            return
        
        print(f"✅ Found User 28:")
        print(f"   - User ID: {test_user.id}")
        print(f"   - Person ID: {test_user.person_id}")
        print(f"   - Email: {test_user.email}")
        
        # Get all vehicles
        asset_stmt = select(Asset).where(
            or_(
                Asset.license_plate == "MNO-345",
                Asset.license_plate == "PQR-678"
            )
        )
        asset_result = await db.execute(asset_stmt)
        assets = asset_result.scalars().all()
        
        print(f"\n✅ Found {len(assets)} vehicles:")
        for asset in assets:
            print(f"\n   Vehicle: {asset.license_plate}")
            print(f"   - Asset ID: {asset.id}")
            print(f"   - Owner Person ID: {asset.owner_person_id}")
            print(f"   - Operator Person ID: {asset.operator_person_id}")
            print(f"   - Owner Org ID: {asset.owner_org_id}")
            print(f"   - Operator Org ID: {asset.operator_org_id}")
            print(f"   - Branch ID: {asset.branch_id}")
            print(f"   - Current Org ID: {asset.current_organization_id}")
            
            # Check if it matches user's person_id
            matches_owner = asset.owner_person_id == test_user.person_id
            matches_operator = asset.operator_person_id == test_user.person_id
            print(f"   - Matches owner_person_id ({test_user.person_id}): {matches_owner}")
            print(f"   - Matches operator_person_id ({test_user.person_id}): {matches_operator}")
        
        # Now test the actual query logic from assets.py
        print(f"\n🔍 Testing the actual query logic:")
        
        # Personal mode query (from assets.py lines 41-57)
        stmt = (
            select(Asset)
            .where(
                or_(
                    Asset.owner_org_id.is_(None),
                    Asset.operator_org_id.is_(None)
                ),
                or_(
                    Asset.owner_person_id == test_user.person_id,
                    Asset.operator_person_id == test_user.person_id
                )
            )
            .order_by(Asset.created_at.desc())
        )
        
        result = await db.execute(stmt)
        personal_assets = result.scalars().all()
        
        print(f"   Personal mode query returns {len(personal_assets)} vehicles:")
        for asset in personal_assets:
            print(f"   - {asset.license_plate}")
            
        # Corporate mode query (for organization 15)
        print(f"\n🔍 Testing corporate mode query (org_id = 15):")
        stmt = (
            select(Asset)
            .where(
                Asset.current_organization_id == 15,
                Asset.branch_id.is_not(None)
            )
            .order_by(Asset.created_at.desc())
        )
        
        result = await db.execute(stmt)
        corporate_assets = result.scalars().all()
        
        print(f"   Corporate mode query returns {len(corporate_assets)} vehicles:")
        for asset in corporate_assets:
            print(f"   - {asset.license_plate}")

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