import sys
import os
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from sqlalchemy.orm import Session
from src.config.database import SessionLocal
from src.models.role import Role
from src.models.room_type import RoomType
from src.models.user import User
import bcrypt
from datetime import datetime

def get_db():
    db = SessionLocal()
    try:
        return db
    finally:
        pass

def seed_roles(db: Session):
    print('=' * 80)
    print('SEEDING ROLES')
    print('=' * 80)
    
    roles_data = [
        {'name': 'admin', 'description': 'Administrator with full access'},
        {'name': 'staff', 'description': 'Staff member with limited admin access'},
        {'name': 'customer', 'description': 'Regular customer'},
        {'name': 'accountant', 'description': 'Accountant role with access to financial data, payments, and invoices'}
    ]
    
    for role_data in roles_data:
        existing = db.query(Role).filter(Role.name == role_data['name']).first()
        if existing:
            print(f'  ✓ Role "{role_data["name"]}" already exists')
        else:
            role = Role(**role_data)
            db.add(role)
            print(f'  ✓ Created role: {role_data["name"]}')
    
    db.commit()
    print('✓ Roles seeded successfully!\n')

def seed_room_types(db: Session):
    print('=' * 80)
    print('SEEDING ROOM TYPES')
    print('=' * 80)
    
    room_types_data = [
        {
            'name': 'Standard Room',
            'description': 'Comfortable and well-appointed standard accommodation',
            'base_price': 150.00,
            'capacity': 2,
            'amenities': ['Free WiFi', 'Air Conditioning', 'TV', 'Minibar', 'Safe']
        },
        {
            'name': 'Superior Room',
            'description': 'Spacious room with enhanced amenities and better views',
            'base_price': 200.00,
            'capacity': 2,
            'amenities': ['Free WiFi', 'Air Conditioning', 'Smart TV', 'Minibar', 'Safe', 'Coffee Maker']
        },
        {
            'name': 'Deluxe Room',
            'description': 'Luxurious room with premium furnishings and amenities',
            'base_price': 280.00,
            'capacity': 3,
            'amenities': ['Free WiFi', 'Air Conditioning', 'Smart TV', 'Netflix', 'Minibar', 'Safe', 'Coffee Maker', 'Premium Toiletries']
        },
        {
            'name': 'Executive Suite',
            'description': 'Elegant suite with separate living area and premium amenities',
            'base_price': 400.00,
            'capacity': 4,
            'amenities': ['Free WiFi', 'Air Conditioning', 'Smart TV', 'Netflix', 'Minibar', 'Safe', 'Espresso Machine', 'Premium Toiletries', 'Bathrobes', 'Work Desk']
        },
        {
            'name': 'Presidential Suite',
            'description': 'The ultimate in luxury with expansive space and exclusive amenities',
            'base_price': 800.00,
            'capacity': 6,
            'amenities': ['Free WiFi', 'Air Conditioning', 'Smart TV', 'Netflix', 'Private Bar', 'Jacuzzi', 'Butler Service', 'Premium Toiletries', 'Bathrobes', 'Private Terrace']
        }
    ]
    
    import json
    for rt_data in room_types_data:
        existing = db.query(RoomType).filter(RoomType.name == rt_data['name']).first()
        if existing:
            print(f'  ✓ Room type "{rt_data["name"]}" already exists')
        else:
            amenities = rt_data.pop('amenities')
            room_type = RoomType(**rt_data, amenities=json.dumps(amenities))
            db.add(room_type)
            print(f'  ✓ Created room type: {rt_data["name"]} (€{rt_data["base_price"]:.2f}/night)')
    
    db.commit()
    print('✓ Room types seeded successfully!\n')

def seed_admin_user(db: Session):
    print('=' * 80)
    print('SEEDING ADMIN USER')
    print('=' * 80)
    
    admin_role = db.query(Role).filter(Role.name == 'admin').first()
    if not admin_role:
        print('  ❌ Admin role not found! Please seed roles first.')
        return
    
    admin_email = 'admin@hotel.com'
    existing_admin = db.query(User).filter(User.email == admin_email).first()
    
    if existing_admin:
        print(f'  ✓ Admin user "{admin_email}" already exists')
    else:
        password = 'admin123'  # Default password - should be changed in production
        password_bytes = password.encode('utf-8')
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
        
        admin_user = User(
            email=admin_email,
            password=hashed_password,
            full_name='Administrator',
            role_id=admin_role.id,
            is_active=True,
            currency='EUR'
        )
        db.add(admin_user)
        db.commit()
        print(f'  ✓ Created admin user: {admin_email}')
        print(f'  ⚠️  Default password: admin123 (please change in production!)')
    
    print('✓ Admin user seeded successfully!\n')

def main():
    db = get_db()
    try:
        seed_roles(db)
        seed_room_types(db)
        seed_admin_user(db)
        print('=' * 80)
        print('✅ Initial data seeding completed successfully!')
        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()

