import asyncio
import httpx
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from app.core.database import DATABASE_URL
from app.models.models import Voucher, VoucherBatch, HotspotProfile
from app.routes.vouchers import _get_hotspot_device, _hotspot_adapter
from sqlalchemy import select

async def clean_all():
    engine = create_async_engine(DATABASE_URL)
    async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with async_session() as db:
        print("1. Fetching all active MikroTik adapters...")
        mk, _ = await _get_hotspot_device(db)
        adapter = await _hotspot_adapter(db, mk.id)

        # 1. Delete all hotspot users from RouterOS
        try:
            pool = adapter._get_api()
            try:
                api = pool.get_api()
                users = api.get_resource('/ip/hotspot/user').get()
                print(f"Found {len(users)} users on RouterOS to delete.")
                for u in users:
                    uid = u.get('.id') or u.get('id')
                    name = u.get('name')
                    # Skip default/system users if any
                    if name in ['default']:
                        continue
                    try:
                        api.get_resource('/ip/hotspot/user').remove(id=uid)
                        print(f"Deleted remote user: {name}")
                    except Exception as e:
                        print(f"Failed to delete remote user {name}: {e}")

                # Delete hotspot profiles from RouterOS (except default)
                profiles = api.get_resource('/ip/hotspot/user/profile').get()
                for p in profiles:
                    pname = p.get('name')
                    pid = p.get('.id') or p.get('id')
                    if pname in ['default', 'default-trial']:
                        continue
                    try:
                        api.get_resource('/ip/hotspot/user/profile').remove(id=pid)
                        print(f"Deleted remote profile: {pname}")
                    except Exception as e:
                        print(f"Failed to delete remote profile {pname}: {e}")
            finally:
                pool.disconnect()
        except Exception as exc:
            print(f"Error communicating with RouterOS during cleanup: {exc}")

        # 2. Clear Vouchers and Batches from DB
        print("2. Clearing vouchers, batches, and profiles from database...")
        vouchers = (await db.execute(select(Voucher))).scalars().all()
        for v in vouchers:
            await db.delete(v)

        batches = (await db.execute(select(VoucherBatch))).scalars().all()
        for b in batches:
            await db.delete(b)

        profiles = (await db.execute(select(HotspotProfile))).scalars().all()
        for p in profiles:
            await db.delete(p)

        await db.commit()
        print("Database fully cleaned!")

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