"""
Footer Page Seeder
Seeds the database with comprehensive footer content
"""
import json
import sys
from pathlib import Path
from datetime import datetime, timezone

# Add parent directory to path to allow importing from src
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.content.models.page_content import PageContent, PageType

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

logger = get_logger(__name__)


def get_footer_page_data():
    """Generate comprehensive footer page data"""
    
    now = datetime.now(timezone.utc)
    
    return {
        'page_type': PageType.FOOTER,
        'title': 'Luxury Hotel & Resort',
        'subtitle': 'Experience Unparalleled Elegance and Comfort',
        'description': 'Your premier destination for luxury hospitality. Experience world-class service, exquisite accommodations, and unforgettable moments.',
        'content': '<p>For over three decades, we have been crafting exceptional experiences for discerning travelers worldwide. Our commitment to excellence and attention to detail sets us apart.</p>',
        'social_links': json.dumps({
            'facebook': 'https://facebook.com/luxuryhotel',
            'twitter': 'https://twitter.com/luxuryhotel',
            'instagram': 'https://instagram.com/luxuryhotel',
            'linkedin': 'https://linkedin.com/company/luxuryhotel',
            'youtube': 'https://youtube.com/luxuryhotel',
            'pinterest': 'https://pinterest.com/luxuryhotel'
        }),
        'footer_links': json.dumps({
            'quick_links': [
                {'label': 'Home', 'url': '/'},
                {'label': 'About Us', 'url': '/about'},
                {'label': 'Rooms & Suites', 'url': '/rooms'},
                {'label': 'Services', 'url': '/services'},
                {'label': 'Contact', 'url': '/contact'},
                {'label': 'Blog', 'url': '/blog'}
            ],
            'accommodations': [
                {'label': 'Standard Rooms', 'url': '/rooms?type=standard'},
                {'label': 'Deluxe Rooms', 'url': '/rooms?type=deluxe'},
                {'label': 'Executive Suites', 'url': '/rooms?type=executive'},
                {'label': 'Presidential Suites', 'url': '/rooms?type=presidential'},
                {'label': 'Ocean View Rooms', 'url': '/rooms?type=ocean-view'},
                {'label': 'Family Rooms', 'url': '/rooms?type=family'}
            ],
            'services': [
                {'label': 'Spa & Wellness', 'url': '/services?category=spa'},
                {'label': 'Fine Dining', 'url': '/services?category=dining'},
                {'label': 'Concierge', 'url': '/services?category=concierge'},
                {'label': 'Business Center', 'url': '/services?category=business'},
                {'label': 'Event Planning', 'url': '/services?category=events'},
                {'label': 'Transportation', 'url': '/services?category=transportation'}
            ],
            'information': [
                {'label': 'About Us', 'url': '/about'},
                {'label': 'Our Story', 'url': '/about#story'},
                {'label': 'Awards & Recognition', 'url': '/about#awards'},
                {'label': 'Careers', 'url': '/careers'},
                {'label': 'Press & Media', 'url': '/press'},
                {'label': 'Blog', 'url': '/blog'}
            ],
            'support_links': [
                {'label': 'Contact Us', 'url': '/contact'},
                {'label': 'FAQ', 'url': '/faq'},
                {'label': 'Booking Help', 'url': '/help'},
                {'label': 'Cancellation Policy', 'url': '/cancellation'},
                {'label': 'Privacy Policy', 'url': '/privacy'},
                {'label': 'Terms & Conditions', 'url': '/terms'},
                {'label': 'Refund Policy', 'url': '/refunds'},
                {'label': 'Accessibility', 'url': '/accessibility'}
            ]
        }),
        'badges': json.dumps([
            {
                'icon': 'award',
                'text': '5-Star Rated',
                'description': 'Consistently rated five-star by global travel guides'
            },
            {
                'icon': 'trophy',
                'text': 'Award Winning',
                'description': 'Best Luxury Hotel 2023'
            },
            {
                'icon': 'shield',
                'text': 'Secure Booking',
                'description': 'Your data and payments are protected'
            },
            {
                'icon': 'star',
                'text': '98% Satisfaction',
                'description': 'Guest satisfaction rating'
            },
            {
                'icon': 'leaf',
                'text': 'Eco-Friendly',
                'description': 'Certified green hotel'
            },
            {
                'icon': 'check-circle',
                'text': 'Best Price Guarantee',
                'description': 'We guarantee the best rates'
            }
        ]),
        'copyright_text': f'© {datetime.now(timezone.utc).year} Luxury Hotel & Resort. All rights reserved.',
        'contact_info': json.dumps({
            'phone': '+1 (555) 123-4567',
            'toll_free': '+1 (800) 123-4567',
            'email': 'info@luxuryhotel.com',
            'reservations_email': 'reservations@luxuryhotel.com',
            'address': '123 Luxury Avenue, Premium City, PC 12345, United States'
        }),
        'is_active': True,
        'created_at': now,
        'updated_at': now
    }


def seed_footer_page(db: Session):
    """Seed footer page content into the database"""
    try:
        footer_data = get_footer_page_data()
        
        # Check if footer page content already exists
        existing_content = db.query(PageContent).filter(PageContent.page_type == PageType.FOOTER).first()
        
        if existing_content:
            logger.info('Updating existing footer page content...')
            for key, value in footer_data.items():
                if key not in ['id', 'page_type', 'created_at']:  # Don't update primary key or creation date
                    setattr(existing_content, key, value)
            existing_content.updated_at = datetime.now(timezone.utc)
        else:
            logger.info('Creating new footer page content...')
            footer_page = PageContent(**footer_data)
            db.add(footer_page)
        
        db.commit()
        logger.info('Footer page content seeded successfully!')
    except Exception as e:
        db.rollback()
        logger.error(f'Error seeding footer page: {str(e)}', exc_info=True)
        raise


def main():
    db = SessionLocal()
    try:
        seed_footer_page(db)
    except Exception as e:
        logger.error(f'Failed to seed footer page: {str(e)}', exc_info=True)
        sys.exit(1)
    finally:
        db.close()


if __name__ == '__main__':
    main()

