"""
Service Seeder
Seeds the database with hotel services
All images are from Unsplash (free stock photos)
"""
import json
import sys
from pathlib import Path
from datetime import datetime, timezone
from decimal import Decimal
import re

# Add parent directory to path to import modules
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from sqlalchemy.orm import Session
from src.shared.config.database import SessionLocal
from src.shared.config.logging_config import get_logger
from src.hotel_services.models.service import Service

# Import all models to ensure relationships are loaded correctly
from src.models import *

logger = get_logger(__name__)


def slugify(text):
    """Convert text to URL-friendly slug"""
    text = text.lower()
    text = re.sub(r'[^\w\s-]', '', text)
    text = re.sub(r'[-\s]+', '-', text)
    return text.strip('-')


def get_services_data():
    """Generate comprehensive services data with Unsplash images"""
    now = datetime.now(timezone.utc)
    
    services = [
        # Spa & Wellness Services
        {
            'name': 'Luxury Spa Treatment',
            'description': 'Indulge in our signature spa treatments designed to rejuvenate your mind, body, and soul. Experience ultimate relaxation with our expert therapists.',
            'price': Decimal('150.00'),
            'category': 'Spa & Wellness',
            'slug': 'luxury-spa-treatment',
            'image': 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=1200&h=800&fit=crop',
            'content': '<p>Our luxury spa treatments combine traditional techniques with modern wellness practices. Choose from a variety of massages, facials, and body treatments tailored to your needs.</p>',
            'sections': json.dumps([
                {
                    'type': 'features',
                    'title': 'Treatment Options',
                    'content': 'Swedish Massage, Deep Tissue, Hot Stone, Aromatherapy, Facial Treatments',
                    'alignment': 'left',
                    'is_visible': True
                }
            ]),
            'meta_title': 'Luxury Spa Treatment | Hotel Spa Services',
            'meta_description': 'Experience ultimate relaxation with our luxury spa treatments. Expert therapists, premium products, and serene environment.',
            'meta_keywords': 'spa, massage, wellness, relaxation, hotel spa, luxury treatment',
            'is_active': True
        },
        {
            'name': 'Couples Massage',
            'description': 'Share a relaxing experience with your partner in our private couples massage room. Perfect for romantic getaways and special occasions.',
            'price': Decimal('280.00'),
            'category': 'Spa & Wellness',
            'slug': 'couples-massage',
            'image': 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=1200&h=800&fit=crop',
            'content': '<p>Enjoy a synchronized massage experience with your loved one in our beautifully appointed couples suite. Includes champagne and chocolate-covered strawberries.</p>',
            'sections': None,
            'meta_title': 'Couples Massage | Romantic Spa Experience',
            'meta_description': 'Share a romantic spa experience with couples massage. Private suite, synchronized treatments, and special amenities included.',
            'meta_keywords': 'couples massage, romantic spa, couples treatment, hotel spa',
            'is_active': True
        },
        {
            'name': 'Facial Treatment',
            'description': 'Rejuvenate your skin with our professional facial treatments using premium skincare products. Customized for your skin type.',
            'price': Decimal('120.00'),
            'category': 'Spa & Wellness',
            'slug': 'facial-treatment',
            'image': 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=1200&h=800&fit=crop',
            'content': '<p>Our expert estheticians provide personalized facial treatments to address your specific skin concerns. Includes deep cleansing, exfoliation, and hydration.</p>',
            'sections': None,
            'meta_title': 'Facial Treatment | Professional Skincare Services',
            'meta_description': 'Professional facial treatments with premium products. Customized for your skin type by expert estheticians.',
            'meta_keywords': 'facial, skincare, spa facial, beauty treatment',
            'is_active': True
        },
        
        # Dining Services
        {
            'name': 'Fine Dining Experience',
            'description': 'Savor exquisite cuisine at our award-winning restaurant. Chef-prepared meals with the finest ingredients and impeccable service.',
            'price': Decimal('200.00'),
            'category': 'Dining',
            'slug': 'fine-dining-experience',
            'image': 'https://images.unsplash.com/photo-1414235077428-338989a2e8c0?w=1200&h=800&fit=crop',
            'content': '<p>Experience culinary excellence at our Michelin-starred restaurant. Our talented chefs create innovative dishes using locally sourced, seasonal ingredients.</p>',
            'sections': json.dumps([
                {
                    'type': 'menu',
                    'title': 'Signature Dishes',
                    'content': 'Truffle Risotto, Wagyu Beef, Lobster Thermidor, Seasonal Tasting Menu',
                    'alignment': 'center',
                    'is_visible': True
                }
            ]),
            'meta_title': 'Fine Dining Restaurant | Award-Winning Cuisine',
            'meta_description': 'Experience award-winning fine dining with chef-prepared meals, premium ingredients, and exceptional service.',
            'meta_keywords': 'fine dining, restaurant, gourmet, Michelin, hotel restaurant',
            'is_active': True
        },
        {
            'name': 'Room Service',
            'description': 'Enjoy delicious meals in the comfort of your room. Available 24/7 with an extensive menu of international and local cuisine.',
            'price': Decimal('50.00'),
            'category': 'Dining',
            'slug': 'room-service',
            'image': 'https://images.unsplash.com/photo-1551632811-5617803d319f?w=1200&h=800&fit=crop',
            'content': '<p>Our room service menu features breakfast, lunch, dinner, and late-night options. All dishes are prepared fresh and delivered to your room with professional service.</p>',
            'sections': None,
            'meta_title': '24/7 Room Service | In-Room Dining',
            'meta_description': 'Enjoy delicious meals in your room with our 24/7 room service. Extensive menu, fresh preparation, and professional delivery.',
            'meta_keywords': 'room service, in-room dining, hotel food delivery',
            'is_active': True
        },
        {
            'name': 'Private Chef Service',
            'description': 'Experience gourmet dining in the privacy of your suite with a personal chef. Customized menus and intimate dining experience.',
            'price': Decimal('500.00'),
            'category': 'Dining',
            'slug': 'private-chef-service',
            'image': 'https://images.unsplash.com/photo-1577219491135-ce391730fd43?w=1200&h=800&fit=crop',
            'content': '<p>Our private chef service brings fine dining directly to your suite. Work with our chef to create a customized menu for your special occasion.</p>',
            'sections': None,
            'meta_title': 'Private Chef Service | In-Suite Dining',
            'meta_description': 'Enjoy a private chef experience in your suite. Customized menus, intimate dining, and exceptional culinary expertise.',
            'meta_keywords': 'private chef, in-suite dining, personal chef, luxury dining',
            'is_active': True
        },
        
        # Concierge Services
        {
            'name': '24/7 Concierge Service',
            'description': 'Our dedicated concierge team is available around the clock to assist with restaurant reservations, event tickets, transportation, and more.',
            'price': Decimal('0.00'),
            'category': 'Concierge',
            'slug': 'concierge-service',
            'image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=800&fit=crop',
            'content': '<p>From restaurant reservations to exclusive experiences, our concierge team ensures your stay is seamless and memorable. Available 24/7 for all your needs.</p>',
            'sections': json.dumps([
                {
                    'type': 'services',
                    'title': 'Concierge Services',
                    'content': 'Restaurant Reservations, Event Tickets, Transportation, City Tours, Special Occasions',
                    'alignment': 'left',
                    'is_visible': True
                }
            ]),
            'meta_title': '24/7 Concierge Service | Personal Assistance',
            'meta_description': 'Round-the-clock concierge service for restaurant reservations, tickets, transportation, and personalized assistance.',
            'meta_keywords': 'concierge, personal assistant, hotel concierge, guest services',
            'is_active': True
        },
        {
            'name': 'Airport Transfer',
            'description': 'Enjoy seamless airport transfers in our luxury vehicles. Professional drivers and comfortable transportation to and from the airport.',
            'price': Decimal('80.00'),
            'category': 'Transportation',
            'slug': 'airport-transfer',
            'image': 'https://images.unsplash.com/photo-1583485088076-494435075764?w=1200&h=800&fit=crop',
            'content': '<p>Start and end your journey in comfort with our premium airport transfer service. Available for all major airports with luxury vehicles and professional drivers.</p>',
            'sections': None,
            'meta_title': 'Airport Transfer Service | Luxury Transportation',
            'meta_description': 'Premium airport transfer service with luxury vehicles and professional drivers. Seamless transportation to and from the airport.',
            'meta_keywords': 'airport transfer, transportation, airport shuttle, luxury car service',
            'is_active': True
        },
        {
            'name': 'City Tour Service',
            'description': 'Discover the city with our guided tour service. Customized itineraries and expert local guides to show you the best attractions.',
            'price': Decimal('150.00'),
            'category': 'Concierge',
            'slug': 'city-tour-service',
            'image': 'https://images.unsplash.com/photo-1488646953014-85cb44e25828?w=1200&h=800&fit=crop',
            'content': '<p>Explore the city with our professional tour guides. Choose from standard tours or customize your itinerary to visit your preferred attractions.</p>',
            'sections': None,
            'meta_title': 'City Tour Service | Guided Tours',
            'meta_description': 'Discover the city with our guided tour service. Expert guides, customized itineraries, and memorable experiences.',
            'meta_keywords': 'city tour, guided tour, sightseeing, local attractions',
            'is_active': True
        },
        
        # Business Services
        {
            'name': 'Business Center Access',
            'description': 'Access our fully equipped business center with computers, printers, meeting rooms, and high-speed internet. Perfect for business travelers.',
            'price': Decimal('25.00'),
            'category': 'Business',
            'slug': 'business-center-access',
            'image': 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=1200&h=800&fit=crop',
            'content': '<p>Our business center provides all the facilities you need for productive work. Includes private workstations, printing services, and meeting spaces.</p>',
            'sections': None,
            'meta_title': 'Business Center | Professional Workspace',
            'meta_description': 'Fully equipped business center with computers, printers, meeting rooms, and high-speed internet for business travelers.',
            'meta_keywords': 'business center, workspace, meeting room, business facilities',
            'is_active': True
        },
        {
            'name': 'Meeting Room Rental',
            'description': 'Host your business meetings in our state-of-the-art meeting rooms. Equipped with modern technology and professional amenities.',
            'price': Decimal('300.00'),
            'category': 'Business',
            'slug': 'meeting-room-rental',
            'image': 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=1200&h=800&fit=crop',
            'content': '<p>Our meeting rooms accommodate various group sizes and are equipped with AV equipment, high-speed internet, and catering options.</p>',
            'sections': None,
            'meta_title': 'Meeting Room Rental | Business Facilities',
            'meta_description': 'State-of-the-art meeting rooms with modern technology, AV equipment, and professional amenities for your business needs.',
            'meta_keywords': 'meeting room, conference room, business meeting, event space',
            'is_active': True
        },
        
        # Additional Services
        {
            'name': 'Laundry & Dry Cleaning',
            'description': 'Professional laundry and dry cleaning services. Same-day service available for your convenience.',
            'price': Decimal('30.00'),
            'category': 'Housekeeping',
            'slug': 'laundry-dry-cleaning',
            'image': 'https://images.unsplash.com/photo-1582735689369-4fe89db7114c?w=1200&h=800&fit=crop',
            'content': '<p>Keep your wardrobe fresh with our professional laundry and dry cleaning services. Same-day service available for urgent needs.</p>',
            'sections': None,
            'meta_title': 'Laundry & Dry Cleaning Service',
            'meta_description': 'Professional laundry and dry cleaning services with same-day service available. Keep your wardrobe fresh during your stay.',
            'meta_keywords': 'laundry, dry cleaning, clothing service, hotel laundry',
            'is_active': True
        },
        {
            'name': 'Fitness Center Access',
            'description': 'Access our state-of-the-art fitness center with modern equipment, personal trainers, and group fitness classes.',
            'price': Decimal('0.00'),
            'category': 'Fitness',
            'slug': 'fitness-center-access',
            'image': 'https://images.unsplash.com/photo-1534438747741-0bf23ca35f0d?w=1200&h=800&fit=crop',
            'content': '<p>Maintain your fitness routine in our fully equipped gym. Features cardio equipment, weight training, and personal training sessions available.</p>',
            'sections': None,
            'meta_title': 'Fitness Center | Hotel Gym Access',
            'meta_description': 'State-of-the-art fitness center with modern equipment, personal trainers, and group fitness classes. Stay fit during your stay.',
            'meta_keywords': 'fitness center, gym, workout, exercise, hotel gym',
            'is_active': True
        },
        {
            'name': 'Personal Shopper',
            'description': 'Discover the city\'s best boutiques and shopping destinations with our expert personal shopper. Tailored shopping experiences.',
            'price': Decimal('200.00'),
            'category': 'Concierge',
            'slug': 'personal-shopper',
            'image': 'https://images.unsplash.com/photo-1528716321680-815a8cdb8bc7?w=1200&h=800&fit=crop',
            'content': '<p>Let our personal shopper guide you to the best shopping destinations. From luxury boutiques to local markets, we\'ll help you find exactly what you\'re looking for.</p>',
            'sections': None,
            'meta_title': 'Personal Shopper Service | Shopping Assistance',
            'meta_description': 'Expert personal shopper service to guide you to the best boutiques and shopping destinations. Tailored shopping experiences.',
            'meta_keywords': 'personal shopper, shopping service, boutique shopping, shopping guide',
            'is_active': True
        },
        {
            'name': 'Valet Parking',
            'description': 'Complimentary valet parking service for all hotel guests. Secure parking with professional valet attendants.',
            'price': Decimal('0.00'),
            'category': 'Transportation',
            'slug': 'valet-parking',
            'image': 'https://images.unsplash.com/photo-1502877338535-766e1452684a?w=1200&h=800&fit=crop',
            'content': '<p>Enjoy the convenience of valet parking. Our professional attendants will safely park and retrieve your vehicle whenever needed.</p>',
            'sections': None,
            'meta_title': 'Valet Parking Service | Complimentary Parking',
            'meta_description': 'Complimentary valet parking service with professional attendants. Secure and convenient parking for all hotel guests.',
            'meta_keywords': 'valet parking, parking service, hotel parking',
            'is_active': True
        },
        {
            'name': 'Butler Service',
            'description': 'Experience personalized butler service for suite guests. Available 24/7 to attend to your every need and ensure a flawless stay.',
            'price': Decimal('0.00'),
            'category': 'Concierge',
            'slug': 'butler-service',
            'image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=800&fit=crop',
            'content': '<p>Our dedicated butlers provide personalized service to suite guests. From unpacking to arranging special requests, we ensure every detail is perfect.</p>',
            'sections': None,
            'meta_title': 'Butler Service | Personalized Assistance',
            'meta_description': 'Personalized butler service for suite guests. Available 24/7 to attend to your every need and ensure a flawless stay.',
            'meta_keywords': 'butler service, personal butler, suite service, luxury service',
            'is_active': True
        },
        {
            'name': 'Event Planning',
            'description': 'Let our expert event planners organize your special occasion. From intimate dinners to grand celebrations, we handle every detail.',
            'price': Decimal('500.00'),
            'category': 'Events',
            'slug': 'event-planning',
            'image': 'https://images.unsplash.com/photo-1519167758481-83f29da1c4fe?w=1200&h=800&fit=crop',
            'content': '<p>Our event planning team will work with you to create unforgettable celebrations. From venue selection to catering and entertainment, we manage it all.</p>',
            'sections': None,
            'meta_title': 'Event Planning Service | Special Occasions',
            'meta_description': 'Expert event planning service for special occasions. From intimate dinners to grand celebrations, we handle every detail.',
            'meta_keywords': 'event planning, party planning, special events, celebration planning',
            'is_active': True
        },
        {
            'name': 'Photography Service',
            'description': 'Capture your special moments with our professional photography service. Available for events, portraits, and special occasions.',
            'price': Decimal('300.00'),
            'category': 'Events',
            'slug': 'photography-service',
            'image': 'https://images.unsplash.com/photo-1516035069371-29a1b244cc32?w=1200&h=800&fit=crop',
            'content': '<p>Our professional photographers will capture your special moments with artistic flair. Perfect for weddings, anniversaries, and other celebrations.</p>',
            'sections': None,
            'meta_title': 'Professional Photography Service',
            'meta_description': 'Professional photography service for events, portraits, and special occasions. Capture your special moments with artistic flair.',
            'meta_keywords': 'photography, photographer, event photography, portrait photography',
            'is_active': True
        },
        {
            'name': 'Babysitting Service',
            'description': 'Professional babysitting service for families. Certified caregivers available to watch your children while you enjoy your stay.',
            'price': Decimal('50.00'),
            'category': 'Family',
            'slug': 'babysitting-service',
            'image': 'https://images.unsplash.com/photo-1503454537195-1dcabb73ffb9?w=1200&h=800&fit=crop',
            'content': '<p>Enjoy peace of mind with our professional babysitting service. All caregivers are certified and experienced in childcare.</p>',
            'sections': None,
            'meta_title': 'Babysitting Service | Childcare',
            'meta_description': 'Professional babysitting service with certified caregivers. Enjoy your stay while your children are safely cared for.',
            'meta_keywords': 'babysitting, childcare, kids service, family service',
            'is_active': True
        }
    ]
    
    return services


def seed_services(db: Session, clear_existing: bool = False):
    """Seed services into the database"""
    try:
        if clear_existing:
            logger.info('Clearing existing services...')
            db.query(Service).delete()
            db.commit()
            logger.info('Existing services cleared.')
        
        services_data = get_services_data()
        now = datetime.now(timezone.utc)
        
        created_count = 0
        updated_count = 0
        
        for service_data in services_data:
            # Generate slug if not provided
            if not service_data.get('slug'):
                service_data['slug'] = slugify(service_data['name'])
            
            existing = db.query(Service).filter(Service.slug == service_data['slug']).first()
            
            if existing:
                logger.debug(f"Service '{service_data['name']}' already exists. Updating...")
                for key, value in service_data.items():
                    setattr(existing, key, value)
                existing.updated_at = now
                updated_count += 1
            else:
                logger.debug(f"Creating service: {service_data['name']}")
                service = Service(
                    **service_data,
                    created_at=now,
                    updated_at=now
                )
                db.add(service)
                created_count += 1
        
        db.commit()
        logger.info(f'Successfully seeded services! Created: {created_count}, Updated: {updated_count}, Total: {len(services_data)}')
    except Exception as e:
        db.rollback()
        logger.error(f'Error seeding services: {str(e)}', exc_info=True)
        raise


def main():
    import argparse
    
    parser = argparse.ArgumentParser(description='Seed hotel services')
    parser.add_argument(
        '--clear',
        action='store_true',
        help='Clear existing services before seeding'
    )
    args = parser.parse_args()
    
    db = SessionLocal()
    try:
        seed_services(db, clear_existing=args.clear)
    except Exception as e:
        logger.error(f'Failed to seed services: {str(e)}', exc_info=True)
        sys.exit(1)
    finally:
        db.close()


if __name__ == '__main__':
    main()

