"""
Refund Policy Page Seeder
Seeds the database with comprehensive refund 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_refunds_page_data():
    """Generate comprehensive refund policy page data"""
    
    now = datetime.now(timezone.utc)
    
    return {
        'page_type': PageType.REFUNDS,
        'title': 'Refund Policy',
        'subtitle': 'Our Refund Policy and Procedures',
        'description': 'Learn about our refund policy, including eligibility, processing times, and how to request a refund for your reservation or services.',
        'content': """
            <h2>1. Overview</h2>
            <p>At Luxury Hotel & Resort, we strive to provide exceptional service and ensure your satisfaction. This Refund Policy outlines the terms and conditions under which refunds may be issued for reservations, services, and other transactions.</p>
            
            <h2>2. Reservation Refunds</h2>
            <h3>2.1 Cancellation Refunds</h3>
            <p>Refunds for cancelled reservations are subject to the cancellation policy associated with your booking:</p>
            <ul>
                <li><strong>Flexible Rate:</strong> Full refund if cancelled 24-48 hours before check-in (depending on rate terms)</li>
                <li><strong>Non-Refundable Rate:</strong> No refund for cancellations, but may be eligible for credit or rescheduling (subject to terms)</li>
                <li><strong>Special Packages:</strong> Refund terms vary by package - please refer to your booking confirmation</li>
            </ul>
            
            <h3>2.2 Early Departure</h3>
            <p>If you check out earlier than your scheduled departure date, you may be eligible for a partial refund for unused nights, subject to the terms of your reservation and availability. Early departure refunds are not guaranteed and are evaluated on a case-by-case basis.</p>
            
            <h3>2.3 No-Show</h3>
            <p>If you do not arrive on your scheduled check-in date and have not cancelled your reservation, you will be charged for the first night. No refunds are provided for no-show reservations.</p>
            
            <h2>3. Service Refunds</h2>
            <h3>3.1 Spa Services</h3>
            <p>Spa service refunds or rescheduling:</p>
            <ul>
                <li>Cancellations made 24 hours in advance: Full refund or rescheduling</li>
                <li>Cancellations made less than 24 hours in advance: 50% refund or rescheduling</li>
                <li>No-show: No refund</li>
            </ul>
            
            <h3>3.2 Dining Reservations</h3>
            <p>Dining reservation refunds:</p>
            <ul>
                <li>Cancellations made 4 hours in advance: Full refund</li>
                <li>Cancellations made less than 4 hours in advance: No refund, but may be rescheduled</li>
                <li>Special event dining: Subject to specific event terms</li>
            </ul>
            
            <h3>3.3 Event & Meeting Bookings</h3>
            <p>Refund policies for events and meetings vary based on the size and type of event. Please refer to your event contract for specific refund terms.</p>
            
            <h2>4. Processing Refunds</h2>
            <h3>4.1 Refund Processing Time</h3>
            <p>Once approved, refunds are typically processed within 5-10 business days. The time it takes for the refund to appear in your account depends on your financial institution:</p>
            <ul>
                <li>Credit card refunds: 5-10 business days</li>
                <li>Debit card refunds: 5-10 business days</li>
                <li>Bank transfer refunds: 7-14 business days</li>
            </ul>
            
            <h3>4.2 Refund Method</h3>
            <p>Refunds will be issued to the original payment method used for the transaction. If the original payment method is no longer valid, please contact us to arrange an alternative refund method.</p>
            
            <h2>5. Requesting a Refund</h2>
            <h3>5.1 How to Request</h3>
            <p>To request a refund, please contact us:</p>
            <ul>
                <li><strong>Phone:</strong> +1 (555) 123-4567</li>
                <li><strong>Email:</strong> refunds@luxuryhotel.com</li>
                <li><strong>Online:</strong> Through your booking confirmation or account</li>
            </ul>
            
            <h3>5.2 Required Information</h3>
            <p>When requesting a refund, please provide:</p>
            <ul>
                <li>Reservation or booking confirmation number</li>
                <li>Guest name and contact information</li>
                <li>Reason for refund request</li>
                <li>Original payment method details</li>
            </ul>
            
            <h2>6. Non-Refundable Items</h2>
            <p>The following items and services are generally non-refundable:</p>
            <ul>
                <li>Non-refundable rate bookings (unless otherwise specified)</li>
                <li>Gift cards and vouchers (subject to terms and conditions)</li>
                <li>Third-party bookings (subject to third-party policies)</li>
                <li>Consumed services (meals, spa treatments already received)</li>
                <li>No-show charges</li>
            </ul>
            
            <h2>7. Special Circumstances</h2>
            <h3>7.1 Force Majeure</h3>
            <p>In cases of force majeure events (natural disasters, pandemics, government restrictions, etc.), we will work with you to provide refunds, credits, or rescheduling options. Each situation is evaluated individually.</p>
            
            <h3>7.2 Service Issues</h3>
            <p>If you experience service issues during your stay, please bring them to our attention immediately so we can address them. We may offer partial refunds or credits for significant service failures, evaluated on a case-by-case basis.</p>
            
            <h2>8. Disputes & Appeals</h2>
            <p>If you are not satisfied with a refund decision, you may appeal by contacting our guest relations team. We will review your case and provide a response within 5-7 business days.</p>
            
            <h2>9. Third-Party Bookings</h2>
            <p>If you made your reservation through a third-party booking site (such as Expedia, Booking.com, etc.), refund requests must be processed through that third party according to their policies. We cannot directly process refunds for third-party bookings.</p>
            
            <h2>10. Contact Information</h2>
            <p>For refund inquiries or assistance, please contact us:</p>
            <ul>
                <li><strong>Refunds Department:</strong> refunds@luxuryhotel.com</li>
                <li><strong>Phone:</strong> +1 (555) 123-4567</li>
                <li><strong>Hours:</strong> Monday-Friday, 9:00 AM - 6:00 PM EST</li>
                <li><strong>Address:</strong> 123 Luxury Avenue, Premium City, PC 12345, United States</li>
            </ul>
            
            <h2>11. Policy Updates</h2>
            <p>We reserve the right to update this Refund Policy at any time. Changes will be posted on this page with an updated "Last Updated" date. Your continued use of our services after changes are posted constitutes acceptance of the updated policy.</p>
            
            <p><em>Last Updated: {}</em></p>
        """.format(now.strftime('%B %d, %Y')),
        'meta_title': 'Refund Policy | Luxury Hotel & Resort',
        'meta_description': 'Learn about our refund policy, including eligibility, processing times, and how to request refunds for reservations and services.',
        'meta_keywords': 'refund policy, cancellation refund, hotel refund, booking refund, refund request',
        'og_title': 'Refund Policy - Luxury Hotel & Resort',
        'og_description': 'Our refund policy and procedures. Learn how to request refunds for reservations and services.',
        'og_image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=630&fit=crop',
        'canonical_url': 'https://luxuryhotel.com/refunds',
        'is_active': True,
        'created_at': now,
        'updated_at': now
    }


def seed_refunds_page(db: Session):
    """Seed refunds policy page content into the database"""
    try:
        refunds_data = get_refunds_page_data()
        
        # Check if refunds page content already exists
        existing_content = db.query(PageContent).filter(PageContent.page_type == PageType.REFUNDS).first()
        
        if existing_content:
            logger.info('Updating existing refunds policy page content...')
            for key, value in refunds_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 refunds policy page content...')
            refunds_page = PageContent(**refunds_data)
            db.add(refunds_page)
        
        db.commit()
        logger.info('Refunds policy page content seeded successfully!')
    except Exception as e:
        db.rollback()
        logger.error(f'Error seeding refunds policy page: {str(e)}', exc_info=True)
        raise


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


if __name__ == '__main__':
    main()

