"""
Cancellation Policy Page Seeder
Seeds the database with comprehensive cancellation policy 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_cancellation_page_data():
    """Generate comprehensive cancellation policy page data"""
    
    now = datetime.now(timezone.utc)
    
    return {
        'page_type': PageType.CANCELLATION,
        'title': 'Cancellation Policy',
        'subtitle': 'Reservation Cancellation Terms and Conditions',
        'description': 'Learn about our cancellation policy, including cancellation deadlines, fees, and procedures for different rate types.',
        'content': """
            <h2>1. Overview</h2>
            <p>This Cancellation Policy outlines the terms and conditions for cancelling reservations at Luxury Hotel & Resort. Cancellation terms vary by rate type and are clearly stated at the time of booking. Please review this policy carefully before making a reservation.</p>
            
            <h2>2. Standard Cancellation Policy</h2>
            <h3>2.1 Flexible Rate</h3>
            <p>For reservations made with our Flexible Rate:</p>
            <ul>
                <li><strong>Free Cancellation:</strong> Cancellations made 24-48 hours before the scheduled check-in date and time are free of charge</li>
                <li><strong>Late Cancellation:</strong> Cancellations made less than 24 hours before check-in will incur a charge equal to one night's room rate plus taxes</li>
                <li><strong>No-Show:</strong> Failure to arrive on the scheduled check-in date will result in a charge for the entire reservation</li>
            </ul>
            
            <h3>2.2 Non-Refundable Rate</h3>
            <p>For reservations made with our Non-Refundable Rate:</p>
            <ul>
                <li>These rates offer the best value but are non-refundable</li>
                <li>Cancellations or modifications are not permitted</li>
                <li>In exceptional circumstances, we may offer a credit for future stays (subject to management approval)</li>
                <li>No-shows will be charged the full reservation amount</li>
            </ul>
            
            <h3>2.3 Advance Purchase Rate</h3>
            <p>For Advance Purchase rates:</p>
            <ul>
                <li>Full payment is required at the time of booking</li>
                <li>Cancellations made 7 days or more before check-in: Full refund minus a processing fee</li>
                <li>Cancellations made less than 7 days before check-in: No refund</li>
            </ul>
            
            <h2>3. Special Packages and Promotions</h2>
            <p>Cancellation terms for special packages, promotions, and seasonal offers may differ from standard rates. Specific cancellation terms will be clearly stated at the time of booking and in your confirmation email.</p>
            
            <h2>4. Group Bookings</h2>
            <p>For group bookings (typically 10 or more rooms):</p>
            <ul>
                <li>Cancellation terms are specified in the group booking contract</li>
                <li>Generally, cancellations must be made 30-60 days in advance to avoid penalties</li>
                <li>Individual room cancellations within a group may be subject to different terms</li>
                <li>Please refer to your group booking agreement for specific terms</li>
            </ul>
            
            <h2>5. Event and Meeting Bookings</h2>
            <p>Cancellation policies for event and meeting space bookings are detailed in your event contract. Generally:</p>
            <ul>
                <li>Cancellations made 30+ days in advance: Full refund or credit</li>
                <li>Cancellations made 14-30 days in advance: 50% refund or credit</li>
                <li>Cancellations made less than 14 days in advance: No refund</li>
            </ul>
            
            <h2>6. How to Cancel</h2>
            <h3>6.1 Online Cancellation</h3>
            <p>You can cancel your reservation online through:</p>
            <ul>
                <li>Your booking confirmation email (click "Manage Reservation")</li>
                <li>Our website's "Manage Booking" section</li>
                <li>Your account dashboard (if you have an account)</li>
            </ul>
            
            <h3>6.2 Phone Cancellation</h3>
            <p>Call our reservations team:</p>
            <ul>
                <li><strong>Phone:</strong> +1 (555) 123-4567</li>
                <li><strong>Hours:</strong> 24/7</li>
                <li>Please have your confirmation number ready</li>
            </ul>
            
            <h3>6.3 Email Cancellation</h3>
            <p>Send an email to:</p>
            <ul>
                <li><strong>Email:</strong> reservations@luxuryhotel.com</li>
                <li>Include your confirmation number and guest name</li>
                <li>Allow 24-48 hours for email processing</li>
            </ul>
            
            <h2>7. Cancellation Confirmation</h2>
            <p>Upon successful cancellation, you will receive a cancellation confirmation email. Please retain this confirmation for your records. If you do not receive a confirmation, please contact us to verify that your cancellation was processed.</p>
            
            <h2>8. Refunds</h2>
            <p>Refunds for eligible cancellations will be processed to the original payment method within 5-10 business days. The time it takes for the refund to appear in your account depends on your financial institution. For more information, please refer to our Refund Policy.</p>
            
            <h2>9. Modifications vs. Cancellations</h2>
            <h3>9.1 Date Changes</h3>
            <p>Modifying your reservation dates may be treated as a cancellation and rebooking, subject to availability and current rates. Please contact us to discuss modification options.</p>
            
            <h3>9.2 Room Type Changes</h3>
            <p>Changes to room type are subject to availability and rate differences. Additional charges may apply if the new room type has a higher rate.</p>
            
            <h2>10. Force Majeure</h2>
            <p>In cases of force majeure events (natural disasters, pandemics, government restrictions, travel bans, etc.), we will work with you to provide flexible cancellation options, including:</p>
            <ul>
                <li>Full refunds</li>
                <li>Rescheduling without penalty</li>
                <li>Credit for future stays</li>
            </ul>
            <p>Each situation is evaluated individually. Please contact us as soon as possible if you are affected by a force majeure event.</p>
            
            <h2>11. Third-Party Bookings</h2>
            <p>If you made your reservation through a third-party booking site (such as Expedia, Booking.com, etc.), you must cancel through that third party according to their cancellation policies. We cannot directly cancel third-party bookings.</p>
            
            <h2>12. No-Show Policy</h2>
            <p>If you do not arrive on your scheduled check-in date and have not cancelled your reservation:</p>
            <ul>
                <li>Your reservation will be considered a "no-show"</li>
                <li>You will be charged according to your rate's cancellation policy</li>
                <li>Remaining nights may be released for resale</li>
                <li>No refunds are provided for no-show reservations</li>
            </ul>
            
            <h2>13. Early Departure</h2>
            <p>If you check out earlier than your scheduled departure date:</p>
            <ul>
                <li>You may be eligible for a partial refund for unused nights</li>
                <li>Early departure refunds are not guaranteed and are evaluated on a case-by-case basis</li>
                <li>Please notify the front desk at least 24 hours before your early departure</li>
                <li>Refunds are subject to the terms of your original reservation</li>
            </ul>
            
            <h2>14. Special Circumstances</h2>
            <p>We understand that unexpected circumstances may arise. In cases of medical emergencies, family emergencies, or other extenuating circumstances, please contact us immediately. We will review your situation and may offer flexible cancellation options on a case-by-case basis.</p>
            
            <h2>15. Contact Information</h2>
            <p>For cancellation requests or questions about our cancellation policy, please contact us:</p>
            <ul>
                <li><strong>Reservations Phone:</strong> +1 (555) 123-4567 (24/7)</li>
                <li><strong>Reservations Email:</strong> reservations@luxuryhotel.com</li>
                <li><strong>Address:</strong> 123 Luxury Avenue, Premium City, PC 12345, United States</li>
            </ul>
            
            <h2>16. Policy Updates</h2>
            <p>We reserve the right to update this Cancellation Policy at any time. Changes will be posted on this page with an updated "Last Updated" date. The cancellation terms that apply to your reservation are those in effect at the time you made your booking.</p>
            
            <p><em>Last Updated: {}</em></p>
        """.format(now.strftime('%B %d, %Y')),
        'meta_title': 'Cancellation Policy | Luxury Hotel & Resort',
        'meta_description': 'Learn about our cancellation policy, including cancellation deadlines, fees, and procedures for different rate types.',
        'meta_keywords': 'cancellation policy, hotel cancellation, booking cancellation, cancel reservation, cancellation terms',
        'og_title': 'Cancellation Policy - Luxury Hotel & Resort',
        'og_description': 'Reservation cancellation terms and conditions. Learn how to cancel your booking and applicable fees.',
        'og_image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=630&fit=crop',
        'canonical_url': 'https://luxuryhotel.com/cancellation',
        'is_active': True,
        'created_at': now,
        'updated_at': now
    }


def seed_cancellation_page(db: Session):
    """Seed cancellation policy page content into the database"""
    try:
        cancellation_data = get_cancellation_page_data()
        
        # Check if cancellation page content already exists
        existing_content = db.query(PageContent).filter(PageContent.page_type == PageType.CANCELLATION).first()
        
        if existing_content:
            logger.info('Updating existing cancellation policy page content...')
            for key, value in cancellation_data.items():
                if key not in ['id', 'page_type', 'created_at']:
                    setattr(existing_content, key, value)
            existing_content.updated_at = datetime.now(timezone.utc)
        else:
            logger.info('Creating new cancellation policy page content...')
            cancellation_page = PageContent(**cancellation_data)
            db.add(cancellation_page)
        
        db.commit()
        logger.info('Cancellation policy page content seeded successfully!')
    except Exception as e:
        db.rollback()
        logger.error(f'Error seeding cancellation policy page: {str(e)}', exc_info=True)
        raise


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


if __name__ == '__main__':
    main()

