import sys
import os
import json
import re
from pathlib import Path
# Add parent directory to path to import from src
sys.path.insert(0, str(Path(__file__).parent.parent))
from sqlalchemy.orm import Session
from src.shared.config.database import SessionLocal
# Import all models to ensure relationships are set up
from src.models import *  # This ensures all models are loaded and relationships are configured
from src.hotel_services.models.service import Service

def generate_slug(name: str) -> str:
    """Generate a URL-friendly slug from a name"""
    slug = name.lower()
    slug = re.sub(r'[^a-z0-9\s-]', '', slug)
    slug = re.sub(r'\s+', '-', slug)
    slug = re.sub(r'-+', '-', slug)
    return slug.strip('-')

def seed_services(db: Session):
    """Seed initial services data"""
    print('Seeding services...')
    
    services_data = [
        {
            'name': 'Room Service',
            'description': '24/7 in-room dining service with a wide selection of gourmet meals, snacks, and beverages delivered directly to your room.',
            'price': 25.00,
            'category': 'Dining',
            'slug': 'room-service',
            'image': 'https://images.unsplash.com/photo-1556911220-bff31c812dba?w=600',
            'content': '<p>Enjoy the convenience of 24/7 room service with our extensive menu featuring international cuisine, local specialties, and premium beverages. Our professional staff ensures your meals are delivered hot, fresh, and beautifully presented.</p><p>From breakfast in bed to late-night snacks, we cater to all your dining needs with the highest standards of quality and service.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Room Service - Luxury Hotel',
            'meta_description': '24/7 in-room dining service with gourmet meals delivered to your room.',
            'meta_keywords': 'room service, in-room dining, hotel service, 24/7 service',
            'is_active': True
        },
        {
            'name': 'Spa & Massage',
            'description': 'Relaxing spa treatments and professional massage therapy to rejuvenate your mind and body.',
            'price': 120.00,
            'category': 'Wellness',
            'slug': 'spa-massage',
            'image': 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=600',
            'content': '<p>Indulge in our world-class spa treatments designed to restore balance and vitality. Our expert therapists offer a range of services including Swedish massage, deep tissue massage, hot stone therapy, and aromatherapy.</p><p>Each treatment is customized to your preferences, using premium products and ancient techniques to provide an unparalleled wellness experience.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Spa & Massage Services - Luxury Hotel',
            'meta_description': 'Professional spa treatments and massage therapy for ultimate relaxation and rejuvenation.',
            'meta_keywords': 'spa, massage, wellness, relaxation, therapy',
            'is_active': True
        },
        {
            'name': 'Laundry Service',
            'description': 'Professional dry cleaning and laundry service with same-day or next-day delivery options.',
            'price': 15.00,
            'category': 'Housekeeping',
            'slug': 'laundry-service',
            'image': 'https://images.unsplash.com/photo-1582735689369-4fe89db7114c?w=600',
            'content': '<p>Keep your wardrobe fresh and clean with our professional laundry and dry cleaning service. We handle everything from delicate garments to business suits with the utmost care and attention.</p><p>Choose from same-day express service or standard next-day delivery. All items are professionally cleaned, pressed, and returned to your room.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Laundry & Dry Cleaning Service - Luxury Hotel',
            'meta_description': 'Professional laundry and dry cleaning service with same-day or next-day delivery.',
            'meta_keywords': 'laundry, dry cleaning, hotel service, cleaning',
            'is_active': True
        },
        {
            'name': 'Airport Transfer',
            'description': 'Complimentary airport pickup and drop-off service in luxury vehicles with professional drivers.',
            'price': 50.00,
            'category': 'Transportation',
            'slug': 'airport-transfer',
            'image': 'https://images.unsplash.com/photo-1449824913935-59a10b8d2000?w=600',
            'content': '<p>Travel in comfort and style with our premium airport transfer service. Our fleet of luxury vehicles, including sedans and SUVs, ensures a smooth and comfortable journey to or from the airport.</p><p>Our professional drivers are punctual, courteous, and knowledgeable about the local area. Flight monitoring ensures we adjust to any delays or early arrivals.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Airport Transfer Service - Luxury Hotel',
            'meta_description': 'Premium airport pickup and drop-off service in luxury vehicles.',
            'meta_keywords': 'airport transfer, transportation, airport shuttle, luxury car',
            'is_active': True
        },
        {
            'name': 'Concierge Service',
            'description': 'Personalized assistance for restaurant reservations, event tickets, tours, and special requests.',
            'price': 0.00,
            'category': 'Concierge',
            'slug': 'concierge-service',
            'image': 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=600',
            'content': '<p>Our dedicated concierge team is available 24/7 to ensure your stay is nothing short of extraordinary. From restaurant reservations and event tickets to private tours and transportation arrangements, we handle every detail with precision and care.</p><p>Whether you need assistance with business arrangements, special celebrations, or unique local experiences, our concierge team has the expertise and connections to make it happen.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Concierge Services - Luxury Hotel',
            'meta_description': 'Personalized assistance for all your travel and entertainment needs, available 24/7.',
            'meta_keywords': 'concierge, personal assistant, travel services, luxury service',
            'is_active': True
        },
        {
            'name': 'Fitness Center Access',
            'description': 'Access to our state-of-the-art fitness center with modern equipment and personal training options.',
            'price': 20.00,
            'category': 'Wellness',
            'slug': 'fitness-center',
            'image': 'https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=600',
            'content': '<p>Maintain your fitness routine at our fully equipped fitness center featuring the latest cardio and strength training equipment. Our facilities are open 24/7 for your convenience.</p><p>Enhance your workout with personal training sessions, group fitness classes, or yoga sessions led by certified instructors. Towels, water, and fresh fruit are provided.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Fitness Center - Luxury Hotel',
            'meta_description': 'State-of-the-art fitness center with modern equipment and personal training options.',
            'meta_keywords': 'fitness center, gym, workout, exercise, personal training',
            'is_active': True
        },
        {
            'name': 'Business Center',
            'description': 'Fully equipped business center with meeting rooms, printing, copying, and secretarial services.',
            'price': 30.00,
            'category': 'Business',
            'slug': 'business-center',
            'image': 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=600',
            'content': '<p>Stay productive with our fully equipped business center featuring private meeting rooms, high-speed internet, printing and copying services, and professional secretarial support.</p><p>Our meeting rooms can accommodate small groups and are equipped with presentation equipment, video conferencing capabilities, and refreshments.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Business Center Services - Luxury Hotel',
            'meta_description': 'Fully equipped business center with meeting rooms and professional services.',
            'meta_keywords': 'business center, meeting room, conference, office services',
            'is_active': True
        },
        {
            'name': 'Valet Parking',
            'description': 'Secure valet parking service with 24/7 vehicle care and quick retrieval.',
            'price': 35.00,
            'category': 'Transportation',
            'slug': 'valet-parking',
            'image': 'https://images.unsplash.com/photo-1502877338535-766e1452684a?w=600',
            'content': '<p>Enjoy the convenience of valet parking with our professional service. Your vehicle will be safely parked and secured, ready for quick retrieval whenever you need it.</p><p>Our valet team is available 24/7 and can also assist with luggage handling and vehicle care services.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Valet Parking Service - Luxury Hotel',
            'meta_description': 'Secure valet parking service with 24/7 vehicle care and quick retrieval.',
            'meta_keywords': 'valet parking, parking service, car service, vehicle care',
            'is_active': True
        },
        {
            'name': 'Babysitting Service',
            'description': 'Professional and certified babysitting service for your peace of mind.',
            'price': 25.00,
            'category': 'Family',
            'slug': 'babysitting-service',
            'image': 'https://images.unsplash.com/photo-1503454537195-1dcabb73ffb9?w=600',
            'content': '<p>Enjoy your time knowing your children are in safe hands with our professional babysitting service. Our certified caregivers are experienced, background-checked, and trained in child safety and first aid.</p><p>Available for both in-room care and supervised activities, we ensure your children are entertained and well-cared for while you enjoy your stay.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Babysitting Service - Luxury Hotel',
            'meta_description': 'Professional and certified babysitting service for your peace of mind.',
            'meta_keywords': 'babysitting, childcare, kids service, family service',
            'is_active': True
        },
        {
            'name': 'Pet Care Service',
            'description': 'Pet-friendly accommodations with pet care services including walking, feeding, and grooming.',
            'price': 20.00,
            'category': 'Pet Services',
            'slug': 'pet-care-service',
            'image': 'https://images.unsplash.com/photo-1601758228041-f3b2795255f1?w=600',
            'content': '<p>Your furry friends are welcome at our hotel! We offer pet-friendly accommodations and a range of pet care services including daily walks, feeding, and grooming.</p><p>Our pet care team ensures your pets are comfortable and well-cared for during your stay. Pet amenities including beds, bowls, and treats are provided.</p>',
            'sections': json.dumps([]),
            'meta_title': 'Pet Care Services - Luxury Hotel',
            'meta_description': 'Pet-friendly accommodations with professional pet care services.',
            'meta_keywords': 'pet care, pet service, dog walking, pet friendly',
            'is_active': True
        }
    ]
    
    created_count = 0
    updated_count = 0
    
    for service_data in services_data:
        # Check if service already exists by slug
        existing = db.query(Service).filter(Service.slug == service_data['slug']).first()
        
        if existing:
            # Update existing service
            for key, value in service_data.items():
                if key != 'slug':  # Don't update slug
                    setattr(existing, key, value)
            updated_count += 1
            print(f'  ✓ Updated service: {service_data["name"]}')
        else:
            # Create new service
            service = Service(**service_data)
            db.add(service)
            created_count += 1
            print(f'  ✓ Created service: {service_data["name"]}')
    
    db.commit()
    print(f'\n✓ Services seeded successfully!')
    print(f'  - Created: {created_count}')
    print(f'  - Updated: {updated_count}')
    print(f'  - Total: {len(services_data)}\n')

def main():
    db: Session = SessionLocal()
    try:
        print('=' * 80)
        print('SEEDING SERVICES')
        print('=' * 80)
        print()
        seed_services(db)
        print('=' * 80)
        print('✓ All services data seeded successfully!')
        print('=' * 80)
    except Exception as e:
        db.rollback()
        print(f'\n✗ Error seeding services: {e}')
        import traceback
        traceback.print_exc()
        raise
    finally:
        db.close()

if __name__ == '__main__':
    main()

