#!/usr/bin/env python3
"""
Debug the scope_id issue.
"""
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
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import AsyncSessionLocal
from app.models.identity.identity import User
from app.core.security import decode_token

# Token from verification test (hardcoded for now, we'll get it dynamically)
TEST_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyOCIsInJvbGUiOiJhZG1pbiIsInJhbmsiOjEsInNjb3BlX2xldmVsIjoib3JnYW5pemF0aW9uIiwic2NvcGVfaWQiOiIyOCIsImV4cCI6MTc3NDg2MjQwMCwiaWF0IjoxNzQzMzI2NDAwLCJ0eXBlIjoiYWNjZXNzIn0.4Q9n2vQ8q3V7X6Y5Z8A9B0C1D2E3F4G5H6I7J8K9L0"

async def debug():
    async with AsyncSessionLocal() as db:
        # Decode token
        payload = decode_token(TEST_TOKEN)
        print(f"✅ Token payload:")
        print(f"   - sub: {payload.get('sub')}")
        print(f"   - scope_id: {payload.get('scope_id')}")
        print(f"   - scope_level: {payload.get('scope_level')}")
        print(f"   - role: {payload.get('role')}")
        
        # Get user from database
        user_id = payload.get('sub')
        if user_id:
            user_stmt = select(User).where(User.id == int(user_id))
            user_result = await db.execute(user_stmt)
            user = user_result.scalar_one_or_none()
            
            if user:
                print(f"\n✅ User from database (ID: {user.id}):")
                print(f"   - scope_id: {user.scope_id}")
                print(f"   - scope_level: {user.scope_level}")
                print(f"   - person_id: {user.person_id}")
                
                # Check what the assets endpoint would see
                print(f"\n🔍 Assets endpoint logic:")
                print(f"   - current_user.scope_id: {user.scope_id}")
                print(f"   - Type: {type(user.scope_id)}")
                print(f"   - Is None? {user.scope_id is None}")
                print(f"   - == 'None'? {user.scope_id == 'None'}")
                print(f"   - == ''? {user.scope_id == ''}")
                
                if user.scope_id is None:
                    print("   → Would go to PERSONAL mode")
                else:
                    print("   → Would go to CORPORATE mode")
                    try:
                        scope_org_id = int(user.scope_id)
                        print(f"   → scope_org_id: {scope_org_id}")
                    except (ValueError, TypeError):
                        print(f"   → scope_org_id: None (invalid)")

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