import os
import shutil
from app import create_app
from models import db, RoomFile, Room, RoomMemberPermission
from sqlalchemy import text

app = create_app()

def clear_all_data():
    with app.app_context():
        # Delete records in the correct order to handle foreign key constraints
        # 1. Delete all RoomFile records from the database
        RoomFile.query.delete()
        print("All RoomFile records deleted.")

        # 2. Delete all RoomMemberPermission records
        RoomMemberPermission.query.delete()
        print("All RoomMemberPermission records deleted.")

        # 3. Delete all room_members associations
        db.session.execute(text('DELETE FROM room_members'))
        print("All room_members associations deleted.")

        # 4. Delete all Room records
        Room.query.delete()
        print("All Room records deleted.")

        # Commit the database changes
        db.session.commit()
        print("Database cleanup completed.")

def clear_filesystem():
    # 1. Clear the data/rooms directory
    data_root = os.path.join(os.path.dirname(__file__), 'data', 'rooms')
    if os.path.exists(data_root):
        for item in os.listdir(data_root):
            item_path = os.path.join(data_root, item)
            if os.path.isfile(item_path):
                os.remove(item_path)
            elif os.path.isdir(item_path):
                shutil.rmtree(item_path)
        print("Cleared data/rooms directory")

    # 2. Clear the uploads directory except for profile_pics
    uploads_dir = os.path.join(os.path.dirname(__file__), 'uploads')
    if os.path.exists(uploads_dir):
        for item in os.listdir(uploads_dir):
            if item != 'profile_pics':
                item_path = os.path.join(uploads_dir, item)
                if os.path.isfile(item_path):
                    os.remove(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
        print("Cleared uploads directory")

if __name__ == '__main__':
    clear_all_data()
    clear_filesystem()
    print("Cleanup completed successfully!") 