import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
import os, uuid, bcrypt
from datetime import datetime, timezone

async def seed():
    client = AsyncIOMotorClient(os.environ.get('MONGO_URL'))
    db = client[os.environ.get('DB_NAME', 'multisistemas')]
    
    # 1. Ensure gestion_4sat module exists
    existing_mod = await db.modulos.find_one({'codigo': 'gestion_4sat'})
    if not existing_mod:
        await db.modulos.insert_one({
            'id': str(uuid.uuid4()),
            'codigo': 'gestion_4sat',
            'nombre': 'Gestion 4sat',
            'descripcion': 'Gestion operativa, tecnica y financiera para rastreo GPS',
            'icono': 'Satellite',
            'ruta_base': '/gestion4sat',
            'activo': True,
            'created_at': datetime.now(timezone.utc).isoformat()
        })
        print('Module gestion_4sat created')
    else:
        print('Module gestion_4sat already exists')
    
    # 2. Find empresa and add gestion_4sat to modulos_asignados
    demo_empresa = await db.empresas.find_one({})
    if demo_empresa:
        current_mods = demo_empresa.get('modulos_asignados', [])
        if 'gestion_4sat' not in current_mods:
            current_mods.append('gestion_4sat')
            await db.empresas.update_one(
                {'id': demo_empresa['id']},
                {'$set': {'modulos_asignados': current_mods}}
            )
            print(f"Added gestion_4sat to empresa {demo_empresa.get('nombre', 'unknown')} (id: {demo_empresa['id']})")
        else:
            print('gestion_4sat already in empresa modules')
        empresa_id = demo_empresa['id']
    else:
        print('No empresa found!')
        return
    
    # Also check if admin@demo.com has an empresa_id reference
    admin_user = await db.usuarios.find_one({'email': 'admin@demo.com'})
    if admin_user:
        admin_emp = admin_user.get('empresa_id')
        print(f"admin@demo.com empresa_id: {admin_emp}")
        if admin_emp and admin_emp != empresa_id:
            # Also update the admin's empresa
            admin_empresa = await db.empresas.find_one({'id': admin_emp})
            if admin_empresa:
                admin_mods = admin_empresa.get('modulos_asignados', [])
                if 'gestion_4sat' not in admin_mods:
                    admin_mods.append('gestion_4sat')
                    await db.empresas.update_one(
                        {'id': admin_emp},
                        {'$set': {'modulos_asignados': admin_mods}}
                    )
                    print(f"Added gestion_4sat to admin empresa {admin_empresa.get('nombre', 'unknown')}")
                empresa_id = admin_emp

    # 3. Create a test user with ONLY gestion_4sat access
    test_email = 'admin4sat@demo.com'
    pwd_hash = bcrypt.hashpw('Test1234!'.encode(), bcrypt.gensalt()).decode()
    
    existing_user = await db.usuarios.find_one({'email': test_email})
    if existing_user:
        await db.usuarios.update_one({'email': test_email}, {'$set': {
            'modulos_acceso': ['gestion_4sat'],
            'rol': 'admin',
            'empresa_id': empresa_id,
            'password_hash': pwd_hash,
            'password': pwd_hash,
            'activo': True,
        }})
        print(f'User {test_email} updated with gestion_4sat access')
    else:
        await db.usuarios.insert_one({
            'id': str(uuid.uuid4()),
            'email': test_email,
            'nombre': 'Admin 4SAT',
            'rol': 'admin',
            'empresa_id': empresa_id,
            'modulos_acceso': ['gestion_4sat'],
            'password_hash': pwd_hash,
            'password': pwd_hash,
            'activo': True,
            'created_at': datetime.now(timezone.utc).isoformat()
        })
        print(f'User {test_email} created with gestion_4sat access')

    print('Seed complete!')

asyncio.run(seed())
