from core.celery_app import celery_app


@celery_app.task
def cleardb(hard: bool):
    """
    Clear the database based on the 'hard' flag.
    'hard'=True: Drop and recreate all tables.
    'hard'=False: Delete data from tables except users.
    """
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from core.config import settings
    from core.database import Base

    engine = create_engine(settings.DB_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()

    if hard:
        Base.metadata.drop_all(bind=engine)
        Base.metadata.create_all(bind=engine)
        db.commit()
        return {"message": "Database reset (HARD)"}
    else:
        tables = Base.metadata.tables.keys()
        for table_name in tables:
            if table_name != "users":
                table = Base.metadata.tables[table_name]
                print(f"Deleting table: {table_name}")
                db.execute(table.delete())
        db.commit()
        return {"message": "Database cleared"}
