#!/usr/bin/env python3
"""
Master script to seed all test data for the hotel booking system.
This script runs all necessary seed scripts in the correct order.
"""

import sys
import os
from pathlib import Path

# Add the Backend directory to the path
backend_dir = Path(__file__).parent.parent
sys.path.insert(0, str(backend_dir))
# Also add the seeds_data directory like other seed scripts
sys.path.insert(0, str(Path(__file__).parent))

import bcrypt

def ensure_housekeeping_role(db):
    """Ensure housekeeping role exists"""
    from src.models.role import Role
    housekeeping_role = db.query(Role).filter(Role.name == 'housekeeping').first()
    if not housekeeping_role:
        print('Creating housekeeping role...')
        housekeeping_role = Role(name='housekeeping', description='Housekeeping staff role')
        db.add(housekeeping_role)
        db.commit()
        db.refresh(housekeeping_role)
        print('✓ Housekeeping role created')
    return housekeeping_role

def ensure_housekeeping_users(db):
    """Ensure housekeeping users exist"""
    from src.models.role import Role
    from src.models.user import User
    housekeeping_role = db.query(Role).filter(Role.name == 'housekeeping').first()
    if not housekeeping_role:
        print('❌ Housekeeping role not found!')
        return
    
    housekeeping_users = [
        {
            'email': 'housekeeping@gnxsoft.com',
            'password': 'housekeeping123',
            'full_name': 'Housekeeping Staff',
            'phone': '+1 (555) 999-0000'
        },
        {
            'email': 'housekeeping2@gnxsoft.com',
            'password': 'housekeeping123',
            'full_name': 'Housekeeping Staff 2',
            'phone': '+1 (555) 999-0001'
        }
    ]
    
    for user_data in housekeeping_users:
        existing = db.query(User).filter(User.email == user_data['email']).first()
        if not existing:
            password_bytes = user_data['password'].encode('utf-8')
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
            
            user = User(
                email=user_data['email'],
                password=hashed_password,
                full_name=user_data['full_name'],
                phone=user_data['phone'],
                role_id=housekeeping_role.id,
                currency='EUR',
                is_active=True
            )
            db.add(user)
            print(f'  ✓ Created housekeeping user: {user_data["email"]} - Password: {user_data["password"]}')
        else:
            print(f'  ⚠️  Housekeeping user "{user_data["email"]}" already exists')
    
    db.commit()

def main():
    print('=' * 80)
    print('SEEDING ALL TEST DATA FOR HOTEL BOOKING SYSTEM')
    print('=' * 80)
    print()
    
    from src.shared.config.database import SessionLocal
    db = SessionLocal()
    try:
        # Step 1: Ensure housekeeping role exists
        print('Step 1: Ensuring housekeeping role exists...')
        ensure_housekeeping_role(db)
        print()
        
        # Step 2: Ensure housekeeping users exist
        print('Step 2: Ensuring housekeeping users exist...')
        ensure_housekeeping_users(db)
        print()
        
        # Step 3: Import and run seed scripts
        print('Step 3: Running seed scripts...')
        print()
        
        # Import seed modules
        from seeds_data.seed_initial_data import seed_roles, seed_room_types, seed_admin_user
        from seeds_data.seed_users import seed_users
        from seeds_data.seed_rooms import seed_rooms
        from seeds_data.seed_bookings import seed_bookings
        
        # Run seed scripts
        print('Running seed_initial_data...')
        seed_initial_data.seed_roles(db)
        seed_initial_data.seed_room_types(db)
        seed_initial_data.seed_admin_user(db)
        print()
        
        print('Running seed_users...')
        seed_users_module.seed_users(db)
        print()
        
        print('Running seed_rooms...')
        seed_rooms_module.seed_rooms(db)
        print()
        
        print('Running seed_bookings...')
        seed_bookings_module.seed_bookings(db)
        print()
        
        print('=' * 80)
        print('✅ ALL TEST DATA SEEDED SUCCESSFULLY!')
        print('=' * 80)
        print()
        print('📋 Test Accounts:')
        print('  Staff:     staff@gnxsoft.com / staff123')
        print('  Housekeeping: housekeeping@gnxsoft.com / housekeeping123')
        print('  Housekeeping 2: housekeeping2@gnxsoft.com / housekeeping123')
        print('  Customer:  customer@gnxsoft.com / customer123')
        print()
        print('🧪 To test notifications:')
        print('  1. Log in as staff (staff@gnxsoft.com)')
        print('  2. Go to Bookings and mark a checked_in booking as checked_out')
        print('  3. Log in as housekeeping user in another browser/tab')
        print('  4. You should receive a real-time notification about the room needing cleaning')
        print('=' * 80)
        
    except Exception as e:
        print(f'\n❌ Error: {e}')
        import traceback
        traceback.print_exc()
        db.rollback()
    finally:
        db.close()

if __name__ == '__main__':
    main()

