import asyncio
import os
import sys
import uuid
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from dotenv import load_dotenv

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env'))
DATABASE_URL = os.environ.get('DATABASE_URL')
if not DATABASE_URL:
    raise ValueError("DATABASE_URL environment variable is not set")

engine = create_async_engine(DATABASE_URL)
Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def seed_client_admin():
    from app.models.access_models import RoleMaster, ModuleMaster, RoleModulePermission
    async with Session() as db:
        print("Seeding new modules...")
        
        # 1. Ensure ROLE_MANAGEMENT module exists
        role_mod = (await db.execute(select(ModuleMaster).where(ModuleMaster.module_code == 'ROLE_MANAGEMENT'))).scalar_one_or_none()
        if not role_mod:
            role_mod = ModuleMaster(module_code='ROLE_MANAGEMENT', module_name='Role Management', description='Manage roles and permissions')
            db.add(role_mod)
            print(' => Added ROLE_MANAGEMENT module')

        # 2. Ensure SYSTEM_LOGS module exists
        logs_mod = (await db.execute(select(ModuleMaster).where(ModuleMaster.module_code == 'SYSTEM_LOGS'))).scalar_one_or_none()
        if not logs_mod:
            logs_mod = ModuleMaster(module_code='SYSTEM_LOGS', module_name='System Logs', description='Access real-time system logs')
            db.add(logs_mod)
            print(' => Added SYSTEM_LOGS module')

        # 2b. Ensure LOCATIONS module exists
        loc_mod = (await db.execute(select(ModuleMaster).where(ModuleMaster.module_code == 'LOCATIONS'))).scalar_one_or_none()
        if not loc_mod:
            loc_mod = ModuleMaster(module_code='LOCATIONS', module_name='Locations', description='Manage Plant Locations and Stations')
            db.add(loc_mod)
            print(' => Added LOCATIONS module')

        await db.commit()

        print("Seeding Client Admin role...")
        
        # 3. Create or update CLIENT_ADMIN role
        role = (await db.execute(select(RoleMaster).where(RoleMaster.role_code == 'CLIENT_ADMIN'))).scalar_one_or_none()
        if not role:
            role = RoleMaster(role_code='CLIENT_ADMIN', role_name='Admin', description='Admin role for the client')
            db.add(role)
            print(' => Added CLIENT_ADMIN role')
        else:
            # Ensure the display name is exactly "Admin"
            await db.execute(update(RoleMaster).where(RoleMaster.role_code == 'CLIENT_ADMIN').values(role_name='Admin'))
            print(' => Updated CLIENT_ADMIN role name to Admin')

        await db.commit()

        print("Assigning permissions...")
        
        # 4. Grant main ADMIN access to the new modules
        for new_mod in ['ROLE_MANAGEMENT', 'SYSTEM_LOGS', 'LOCATIONS']:
            admin_perm = (await db.execute(select(RoleModulePermission).where(RoleModulePermission.role_code == 'ADMIN', RoleModulePermission.module_code == new_mod))).scalar_one_or_none()
            if not admin_perm:
                admin_perm = RoleModulePermission(id=uuid.uuid4(), role_code='ADMIN', module_code=new_mod, can_view=True, can_create=True, can_edit=True, can_delete=True, can_approve=True)
                db.add(admin_perm)
                print(f' => Granted ADMIN access to {new_mod}')

        # 5. Grant CLIENT_ADMIN access to their exact modules
        # Note: Even though CLIENT_ADMIN has USER_MANAGEMENT, the backend API (routes.py) 
        # strictly prevents them from viewing, creating, or editing the main 'ADMIN' role/users.
        client_modules = ['SALES', 'YARD', 'DEALER_PORTAL_ADMIN', 'USER_MANAGEMENT', 'LOCATIONS']
        for m_code in client_modules:
            perm = (await db.execute(select(RoleModulePermission).where(RoleModulePermission.role_code == 'CLIENT_ADMIN', RoleModulePermission.module_code == m_code))).scalar_one_or_none()
            if not perm:
                perm = RoleModulePermission(id=uuid.uuid4(), role_code='CLIENT_ADMIN', module_code=m_code, can_view=True, can_create=True, can_edit=True, can_delete=True, can_approve=True)
                db.add(perm)
                print(f' => Granted CLIENT_ADMIN access to {m_code}')

        await db.commit()
        print('Done! Client Admin configurations seeded successfully.')

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