"""
Privacy Policy Page Seeder
Seeds the database with comprehensive privacy 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_privacy_page_data():
    """Generate comprehensive privacy policy page data"""
    
    now = datetime.now(timezone.utc)
    
    return {
        'page_type': PageType.PRIVACY,
        'title': 'Privacy Policy',
        'subtitle': 'Your Privacy Matters to Us',
        'description': 'Learn how we collect, use, and protect your personal information. We are committed to maintaining your privacy and ensuring the security of your data.',
        'content': """
            <h2>1. Introduction</h2>
            <p>At Luxury Hotel & Resort, we are committed to protecting your privacy and ensuring the security of your personal information. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you visit our website, make a reservation, or use our services.</p>
            
            <h2>2. Information We Collect</h2>
            <h3>2.1 Personal Information</h3>
            <p>We may collect personal information that you provide directly to us, including:</p>
            <ul>
                <li>Name, email address, phone number, and mailing address</li>
                <li>Payment information (credit card details, billing address)</li>
                <li>Reservation details and preferences</li>
                <li>Identification documents (for check-in purposes)</li>
                <li>Special requests or dietary requirements</li>
            </ul>
            
            <h3>2.2 Automatically Collected Information</h3>
            <p>When you visit our website, we may automatically collect certain information, including:</p>
            <ul>
                <li>IP address and browser type</li>
                <li>Device information and operating system</li>
                <li>Pages visited and time spent on our site</li>
                <li>Referring website addresses</li>
                <li>Cookies and similar tracking technologies</li>
            </ul>
            
            <h2>3. How We Use Your Information</h2>
            <p>We use the information we collect for various purposes, including:</p>
            <ul>
                <li>Processing and managing your reservations</li>
                <li>Communicating with you about your stay</li>
                <li>Providing customer service and support</li>
                <li>Sending marketing communications (with your consent)</li>
                <li>Improving our services and website experience</li>
                <li>Complying with legal obligations</li>
                <li>Preventing fraud and ensuring security</li>
            </ul>
            
            <h2>4. Information Sharing and Disclosure</h2>
            <p>We do not sell your personal information. We may share your information in the following circumstances:</p>
            <ul>
                <li><strong>Service Providers:</strong> With trusted third-party service providers who assist us in operating our business</li>
                <li><strong>Legal Requirements:</strong> When required by law or to protect our rights and safety</li>
                <li><strong>Business Transfers:</strong> In connection with a merger, acquisition, or sale of assets</li>
                <li><strong>With Your Consent:</strong> When you have given us explicit permission to share your information</li>
            </ul>
            
            <h2>5. Data Security</h2>
            <p>We implement appropriate technical and organizational measures to protect your personal information against unauthorized access, alteration, disclosure, or destruction. However, no method of transmission over the Internet is 100% secure, and we cannot guarantee absolute security.</p>
            
            <h2>6. Your Rights</h2>
            <p>Depending on your location, you may have certain rights regarding your personal information, including:</p>
            <ul>
                <li>The right to access your personal information</li>
                <li>The right to correct inaccurate information</li>
                <li>The right to request deletion of your information</li>
                <li>The right to object to processing of your information</li>
                <li>The right to data portability</li>
                <li>The right to withdraw consent</li>
            </ul>
            
            <h2>7. Cookies and Tracking Technologies</h2>
            <p>We use cookies and similar tracking technologies to enhance your browsing experience, analyze website traffic, and personalize content. You can control cookie preferences through your browser settings.</p>
            
            <h2>8. Third-Party Links</h2>
            <p>Our website may contain links to third-party websites. We are not responsible for the privacy practices of these external sites. We encourage you to review their privacy policies.</p>
            
            <h2>9. Children's Privacy</h2>
            <p>Our services are not directed to individuals under the age of 18. We do not knowingly collect personal information from children. If you believe we have collected information from a child, please contact us immediately.</p>
            
            <h2>10. International Data Transfers</h2>
            <p>Your information may be transferred to and processed in countries other than your country of residence. We ensure appropriate safeguards are in place to protect your information in accordance with this Privacy Policy.</p>
            
            <h2>11. Changes to This Privacy Policy</h2>
            <p>We may update this Privacy Policy from time to time. We will notify you of any material changes by posting the new policy on this page and updating the "Last Updated" date.</p>
            
            <h2>12. Contact Us</h2>
            <p>If you have any questions or concerns about this Privacy Policy or our data practices, please contact us at:</p>
            <p>
                <strong>Email:</strong> privacy@luxuryhotel.com<br>
                <strong>Phone:</strong> +1 (555) 123-4567<br>
                <strong>Address:</strong> 123 Luxury Avenue, Premium City, PC 12345, United States
            </p>
            
            <p><em>Last Updated: {}</em></p>
        """.format(now.strftime('%B %d, %Y')),
        'meta_title': 'Privacy Policy | Luxury Hotel & Resort',
        'meta_description': 'Learn how Luxury Hotel & Resort collects, uses, and protects your personal information. Read our comprehensive privacy policy.',
        'meta_keywords': 'privacy policy, data protection, personal information, GDPR, privacy rights, hotel privacy',
        'og_title': 'Privacy Policy - Luxury Hotel & Resort',
        'og_description': 'Your privacy matters to us. Learn how we protect and use your personal information.',
        'og_image': 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&h=630&fit=crop',
        'canonical_url': 'https://luxuryhotel.com/privacy',
        'is_active': True,
        'created_at': now,
        'updated_at': now
    }


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


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


if __name__ == '__main__':
    main()

