"""
Terms of Use Page Seeder
Seeds the database with comprehensive terms of use 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_terms_page_data():
    """Generate comprehensive terms of use page data"""
    
    now = datetime.now(timezone.utc)
    
    return {
        'page_type': PageType.TERMS,
        'title': 'Terms of Use',
        'subtitle': 'Terms and Conditions for Using Our Services',
        'description': 'Please read these terms and conditions carefully before using our website or services. By using our services, you agree to be bound by these terms.',
        'content': """
            <h2>1. Acceptance of Terms</h2>
            <p>By accessing and using the Luxury Hotel & Resort website and services, you accept and agree to be bound by the terms and provision of this agreement. If you do not agree to these terms, please do not use our services.</p>
            
            <h2>2. Use of Website</h2>
            <h3>2.1 Eligibility</h3>
            <p>You must be at least 18 years old to make a reservation or use our services. By using our website, you represent and warrant that you are at least 18 years of age and have the legal capacity to enter into this agreement.</p>
            
            <h3>2.2 User Account</h3>
            <p>If you create an account with us, you are responsible for maintaining the confidentiality of your account and password. You agree to accept responsibility for all activities that occur under your account.</p>
            
            <h3>2.3 Prohibited Uses</h3>
            <p>You agree not to use our website or services:</p>
            <ul>
                <li>For any unlawful purpose or to solicit others to perform unlawful acts</li>
                <li>To violate any international, federal, provincial, or state regulations, rules, laws, or local ordinances</li>
                <li>To infringe upon or violate our intellectual property rights or the intellectual property rights of others</li>
                <li>To harass, abuse, insult, harm, defame, slander, disparage, intimidate, or discriminate</li>
                <li>To submit false or misleading information</li>
                <li>To upload or transmit viruses or any other type of malicious code</li>
                <li>To collect or track the personal information of others</li>
                <li>To spam, phish, pharm, pretext, spider, crawl, or scrape</li>
                <li>For any obscene or immoral purpose</li>
                <li>To interfere with or circumvent the security features of our website</li>
            </ul>
            
            <h2>3. Reservations and Bookings</h2>
            <h3>3.1 Reservation Terms</h3>
            <p>When you make a reservation through our website or by phone, you agree to:</p>
            <ul>
                <li>Provide accurate and complete information</li>
                <li>Use a valid payment method</li>
                <li>Pay all charges incurred by your account</li>
                <li>Comply with our cancellation and refund policies</li>
            </ul>
            
            <h3>3.2 Pricing</h3>
            <p>All prices are displayed in the currency specified and are subject to change without notice. We reserve the right to correct any pricing errors. Taxes and fees may apply and will be disclosed at the time of booking.</p>
            
            <h3>3.3 Payment</h3>
            <p>Payment is required at the time of booking or as specified in your reservation confirmation. We accept major credit cards and other payment methods as indicated on our website.</p>
            
            <h2>4. Cancellation and Refund Policy</h2>
            <p>Cancellation and refund terms vary by rate type and are specified at the time of booking. Please refer to your booking confirmation and our Refund Policy for detailed information.</p>
            
            <h2>5. Intellectual Property</h2>
            <p>The content on our website, including text, graphics, logos, images, and software, is the property of Luxury Hotel & Resort or its content suppliers and is protected by copyright and other intellectual property laws. You may not reproduce, distribute, modify, or create derivative works from any content without our express written permission.</p>
            
            <h2>6. User Content</h2>
            <p>If you submit content to our website (such as reviews, comments, or photos), you grant us a non-exclusive, royalty-free, perpetual, and worldwide license to use, reproduce, modify, and distribute such content for any purpose.</p>
            
            <h2>7. Limitation of Liability</h2>
            <p>To the fullest extent permitted by law, Luxury Hotel & Resort shall not be liable for any indirect, incidental, special, consequential, or punitive damages, or any loss of profits or revenues, whether incurred directly or indirectly, or any loss of data, use, goodwill, or other intangible losses resulting from your use of our services.</p>
            
            <h2>8. Indemnification</h2>
            <p>You agree to indemnify, defend, and hold harmless Luxury Hotel & Resort and its officers, directors, employees, and agents from any claims, damages, losses, liabilities, and expenses (including legal fees) arising out of or relating to your use of our services or violation of these terms.</p>
            
            <h2>9. Disclaimer of Warranties</h2>
            <p>Our services are provided "as is" and "as available" without warranties of any kind, either express or implied. We do not warrant that our services will be uninterrupted, secure, or error-free.</p>
            
            <h2>10. Third-Party Links</h2>
            <p>Our website may contain links to third-party websites. We are not responsible for the content, privacy policies, or practices of third-party websites. Your use of third-party websites is at your own risk.</p>
            
            <h2>11. Force Majeure</h2>
            <p>We shall not be liable for any failure or delay in performance under these terms which is due to circumstances beyond our reasonable control, including but not limited to natural disasters, war, terrorism, pandemics, government actions, or other force majeure events.</p>
            
            <h2>12. Governing Law</h2>
            <p>These terms shall be governed by and construed in accordance with the laws of the jurisdiction in which our hotel is located, without regard to its conflict of law provisions.</p>
            
            <h2>13. Dispute Resolution</h2>
            <p>Any disputes arising out of or relating to these terms or our services shall be resolved through binding arbitration in accordance with the rules of the applicable arbitration association, except where prohibited by law.</p>
            
            <h2>14. Changes to Terms</h2>
            <p>We reserve the right to modify these terms at any time. Changes will be effective immediately upon posting on our website. Your continued use of our services after changes are posted constitutes acceptance of the modified terms.</p>
            
            <h2>15. Severability</h2>
            <p>If any provision of these terms is found to be unenforceable or invalid, that provision shall be limited or eliminated to the minimum extent necessary, and the remaining provisions shall remain in full force and effect.</p>
            
            <h2>16. Entire Agreement</h2>
            <p>These terms constitute the entire agreement between you and Luxury Hotel & Resort regarding the use of our services and supersede all prior agreements and understandings.</p>
            
            <h2>17. Contact Information</h2>
            <p>If you have any questions about these Terms of Use, please contact us:</p>
            <ul>
                <li><strong>Email:</strong> legal@luxuryhotel.com</li>
                <li><strong>Phone:</strong> +1 (555) 123-4567</li>
                <li><strong>Address:</strong> 123 Luxury Avenue, Premium City, PC 12345, United States</li>
            </ul>
            
            <p><em>Last Updated: {}</em></p>
        """.format(now.strftime('%B %d, %Y')),
        'meta_title': 'Terms of Use | Luxury Hotel & Resort - Terms and Conditions',
        'meta_description': 'Read our terms and conditions for using our website and services. By using our services, you agree to these terms.',
        'meta_keywords': 'terms of use, terms and conditions, user agreement, legal terms, hotel terms',
        'og_title': 'Terms of Use - Luxury Hotel & Resort',
        'og_description': 'Terms and conditions for using our website and services. Please read carefully before using our services.',
        'og_image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=630&fit=crop',
        'canonical_url': 'https://luxuryhotel.com/terms',
        'is_active': True,
        'created_at': now,
        'updated_at': now
    }


def seed_terms_page(db: Session):
    """Seed terms of use page content into the database"""
    try:
        terms_data = get_terms_page_data()
        
        # Check if terms page content already exists
        existing_content = db.query(PageContent).filter(PageContent.page_type == PageType.TERMS).first()
        
        if existing_content:
            logger.info('Updating existing terms of use page content...')
            for key, value in terms_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 terms of use page content...')
            terms_page = PageContent(**terms_data)
            db.add(terms_page)
        
        db.commit()
        logger.info('Terms of use page content seeded successfully!')
    except Exception as e:
        db.rollback()
        logger.error(f'Error seeding terms of use page: {str(e)}', exc_info=True)
        raise


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


if __name__ == '__main__':
    main()

