import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from app.core.database import DATABASE_URL
from app.routes.vouchers import _get_hotspot_device, _hotspot_adapter

async def flush_router():
    engine = create_async_engine(DATABASE_URL)
    async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    async with async_session() as db:
        mk, _ = await _get_hotspot_device(db)
        try:
            adapter = await _hotspot_adapter(db, mk.id)
            pool = adapter._get_api()
            try:
                api = pool.get_api()
                users = api.get_resource('/ip/hotspot/user').get()
                for u in users:
                    if u.get('name') != 'default':
                        try:
                            api.get_resource('/ip/hotspot/user').remove(id=u.get('.id') or u.get('id'))
                            print('Removed user:', u.get('name'))
                        except Exception as e:
                            print('Skipped user:', e)
                profiles = api.get_resource('/ip/hotspot/user/profile').get()
                for p in profiles:
                    if p.get('name') not in ['default', 'default-trial']:
                        try:
                            api.get_resource('/ip/hotspot/user/profile').remove(id=p.get('.id') or p.get('id'))
                            print('Removed profile:', p.get('name'))
                        except Exception as e:
                            print('Skipped profile:', e)
            finally:
                pool.disconnect()
        except Exception as exc:
            print("Could not connect to router (credentials may need update):", exc)

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