import os
from datetime import datetime
from app import create_app
from models import db, Room, RoomFile, User

DATA_ROOT = '/app/uploads/rooms'

app = create_app()

with app.app_context():
    admin_user = User.query.filter_by(is_admin=True).first()
    if not admin_user:
        print('No admin user found. Aborting.')
        exit(1)
    rooms = Room.query.all()
    for room in rooms:
        room_dir = os.path.join(DATA_ROOT, str(room.id))
        if not os.path.exists(room_dir):
            continue
        for root, dirs, files in os.walk(room_dir):
            rel_root = os.path.relpath(root, room_dir)
            rel_path = '' if rel_root == '.' else rel_root.replace('\\', '/')
            # Folders
            for d in dirs:
                exists = RoomFile.query.filter_by(room_id=room.id, name=d, path=rel_path, type='folder').first()
                folder_path = os.path.join(root, d)
                stat = os.stat(folder_path)
                if not exists:
                    rf = RoomFile(
                        room_id=room.id,
                        name=d,
                        path=rel_path,
                        type='folder',
                        size=None,
                        modified=stat.st_mtime,
                        uploaded_by=admin_user.id,
                        uploaded_at=datetime.utcfromtimestamp(stat.st_mtime)
                    )
                    db.session.add(rf)
            # Files
            for f in files:
                exists = RoomFile.query.filter_by(room_id=room.id, name=f, path=rel_path, type='file').first()
                file_path = os.path.join(root, f)
                stat = os.stat(file_path)
                if not exists:
                    rf = RoomFile(
                        room_id=room.id,
                        name=f,
                        path=rel_path,
                        type='file',
                        size=stat.st_size,
                        modified=stat.st_mtime,
                        uploaded_by=admin_user.id,
                        uploaded_at=datetime.utcfromtimestamp(stat.st_mtime)
                    )
                    db.session.add(rf)
    db.session.commit()
    print('RoomFile table synchronized with filesystem.') 