#!/usr/bin/env python3
"""
Create Platform Content Pages

This script creates default platform-level content pages:
- Platform Homepage (slug='platform_homepage')
- About Us (slug='about')
- FAQ (slug='faq')
- Terms of Service (slug='terms')
- Privacy Policy (slug='privacy')
- Contact Us (slug='contact')

All pages are created with vendor_id=NULL (platform-level defaults).

Usage:
    python scripts/create_platform_pages.py
"""

import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(project_root))

from app.core.database import SessionLocal
from app.modules.cms.services import content_page_service


def create_platform_pages():
    """Create default platform content pages."""
    db = SessionLocal()

    try:
        print("=" * 80)
        print("CREATING PLATFORM CONTENT PAGES")
        print("=" * 80)
        print()

        # Import ContentPage for checking existing pages
        from app.modules.cms.models import ContentPage

        # ========================================================================
        # 1. PLATFORM HOMEPAGE
        # ========================================================================
        print("1. Creating Platform Homepage...")

        # Check if already exists
        existing = (
            db.query(ContentPage)
            .filter_by(vendor_id=None, slug="platform_homepage")
            .first()
        )
        if existing:
            print(
                f"   ⚠️  Skipped: Platform Homepage - already exists (ID: {existing.id})"
            )
        else:
            try:
                homepage = content_page_service.create_page(
                    db,
                    slug="platform_homepage",
                    title="Welcome to Our Multi-Vendor Marketplace",
                    content="""
                    <p class="lead">
                        Connect vendors with customers worldwide. Build your online store and reach millions of shoppers.
                    </p>
                    <p>
                        Our platform empowers entrepreneurs to launch their own branded e-commerce stores
                        with minimal effort and maximum impact.
                    </p>
                """,
                    template="modern",  # Uses platform/homepage-modern.html
                    vendor_id=None,  # Platform-level page
                    is_published=True,
                    show_in_header=False,  # Homepage is not in menu (it's the root)
                    show_in_footer=False,
                    display_order=0,
                    meta_description="Leading multi-vendor marketplace platform. Connect with thousands of vendors and discover millions of products.",
                    meta_keywords="marketplace, multi-vendor, e-commerce, online shopping, platform",
                )
                print(f"   ✅ Created: {homepage.title} (/{homepage.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: Platform Homepage - {str(e)}")

        # ========================================================================
        # 2. ABOUT US
        # ========================================================================
        print("2. Creating About Us page...")

        existing = db.query(ContentPage).filter_by(vendor_id=None, slug="about").first()
        if existing:
            print(f"   ⚠️  Skipped: About Us - already exists (ID: {existing.id})")
        else:
            try:
                about = content_page_service.create_page(
                    db,
                    slug="about",
                    title="About Us",
                    content="""
                    <h2>Our Mission</h2>
                    <p>
                        We're on a mission to democratize e-commerce by providing powerful,
                        easy-to-use tools for entrepreneurs worldwide.
                    </p>

                    <h2>Our Story</h2>
                    <p>
                        Founded in 2024, our platform has grown to serve over 10,000 active vendors
                        and millions of customers around the globe. We believe that everyone should
                        have the opportunity to build and grow their own online business.
                    </p>

                    <h2>Why Choose Us?</h2>
                    <ul>
                        <li><strong>Easy to Start:</strong> Launch your store in minutes, not months</li>
                        <li><strong>Powerful Tools:</strong> Everything you need to succeed in one platform</li>
                        <li><strong>Scalable:</strong> Grow from startup to enterprise seamlessly</li>
                        <li><strong>Reliable:</strong> 99.9% uptime guarantee with 24/7 support</li>
                    </ul>

                    <h2>Our Values</h2>
                    <ul>
                        <li><strong>Innovation:</strong> We constantly improve and evolve our platform</li>
                        <li><strong>Transparency:</strong> No hidden fees, no surprises</li>
                        <li><strong>Community:</strong> We succeed when our vendors succeed</li>
                        <li><strong>Excellence:</strong> We strive for the highest quality in everything we do</li>
                    </ul>
                """,
                    vendor_id=None,
                    is_published=True,
                    show_in_header=True,  # Show in header navigation
                    show_in_footer=True,  # Show in footer
                    display_order=1,
                    meta_description="Learn about our mission to democratize e-commerce and empower entrepreneurs worldwide.",
                    meta_keywords="about us, mission, vision, values, company",
                )
                print(f"   ✅ Created: {about.title} (/{about.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: About Us - {str(e)}")

        # ========================================================================
        # 3. FAQ
        # ========================================================================
        print("3. Creating FAQ page...")

        existing = db.query(ContentPage).filter_by(vendor_id=None, slug="faq").first()
        if existing:
            print(f"   ⚠️  Skipped: FAQ - already exists (ID: {existing.id})")
        else:
            try:
                faq = content_page_service.create_page(
                    db,
                    slug="faq",
                    title="Frequently Asked Questions",
                    content="""
                    <h2>Getting Started</h2>

                    <h3>How do I create a vendor account?</h3>
                    <p>
                        Contact our sales team to get started. We'll set up your account and provide
                        you with everything you need to launch your store.
                    </p>

                    <h3>How long does it take to set up my store?</h3>
                    <p>
                        Most vendors can launch their store in less than 24 hours. Our team will guide
                        you through the setup process step by step.
                    </p>

                    <h2>Pricing & Payment</h2>

                    <h3>What are your pricing plans?</h3>
                    <p>
                        We offer flexible pricing plans based on your business needs. Contact us for
                        detailed pricing information and to find the plan that's right for you.
                    </p>

                    <h3>When do I get paid?</h3>
                    <p>
                        Payments are processed weekly, with funds typically reaching your account
                        within 2-3 business days.
                    </p>

                    <h2>Features & Support</h2>

                    <h3>Can I customize my store's appearance?</h3>
                    <p>
                        Yes! Our platform supports full theme customization including colors, fonts,
                        logos, and layouts. Make your store truly yours.
                    </p>

                    <h3>What kind of support do you provide?</h3>
                    <p>
                        We offer 24/7 email support for all vendors, with priority phone support
                        available for enterprise plans.
                    </p>

                    <h2>Technical Questions</h2>

                    <h3>Do I need technical knowledge to use the platform?</h3>
                    <p>
                        No! Our platform is designed to be user-friendly for everyone. However, if you
                        want to customize advanced features, our documentation and support team are here to help.
                    </p>

                    <h3>Can I integrate with other tools?</h3>
                    <p>
                        Yes, we support integrations with popular payment gateways, shipping providers,
                        and marketing tools.
                    </p>
                """,
                    vendor_id=None,
                    is_published=True,
                    show_in_header=True,  # Show in header navigation
                    show_in_footer=True,
                    display_order=2,
                    meta_description="Find answers to common questions about our marketplace platform.",
                    meta_keywords="faq, frequently asked questions, help, support",
                )
                print(f"   ✅ Created: {faq.title} (/{faq.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: FAQ - {str(e)}")

        # ========================================================================
        # 4. CONTACT US
        # ========================================================================
        print("4. Creating Contact Us page...")

        existing = (
            db.query(ContentPage).filter_by(vendor_id=None, slug="contact").first()
        )
        if existing:
            print(f"   ⚠️  Skipped: Contact Us - already exists (ID: {existing.id})")
        else:
            try:
                contact = content_page_service.create_page(
                    db,
                    slug="contact",
                    title="Contact Us",
                    content="""
                    <h2>Get in Touch</h2>
                    <p>
                        We'd love to hear from you! Whether you have questions about our platform,
                        need technical support, or want to discuss partnership opportunities, our
                        team is here to help.
                    </p>

                    <h2>Contact Information</h2>
                    <ul>
                        <li><strong>Email:</strong> support@marketplace.com</li>
                        <li><strong>Phone:</strong> +1 (555) 123-4567</li>
                        <li><strong>Hours:</strong> Monday - Friday, 9 AM - 6 PM PST</li>
                    </ul>

                    <h2>Office Address</h2>
                    <p>
                        123 Business Street, Suite 100<br>
                        San Francisco, CA 94102<br>
                        United States
                    </p>

                    <h2>Sales Inquiries</h2>
                    <p>
                        Interested in launching your store on our platform?<br>
                        Email: <a href="mailto:sales@marketplace.com">sales@marketplace.com</a>
                    </p>

                    <h2>Technical Support</h2>
                    <p>
                        Need help with your store?<br>
                        Email: <a href="mailto:support@marketplace.com">support@marketplace.com</a><br>
                        24/7 email support for all vendors
                    </p>

                    <h2>Media & Press</h2>
                    <p>
                        For media inquiries and press releases:<br>
                        Email: <a href="mailto:press@marketplace.com">press@marketplace.com</a>
                    </p>
                """,
                    vendor_id=None,
                    is_published=True,
                    show_in_header=True,  # Show in header navigation
                    show_in_footer=True,
                    display_order=3,
                    meta_description="Get in touch with our team. We're here to help you succeed.",
                    meta_keywords="contact, support, email, phone, address",
                )
                print(f"   ✅ Created: {contact.title} (/{contact.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: Contact Us - {str(e)}")

        # ========================================================================
        # 5. TERMS OF SERVICE
        # ========================================================================
        print("5. Creating Terms of Service page...")

        existing = db.query(ContentPage).filter_by(vendor_id=None, slug="terms").first()
        if existing:
            print(
                f"   ⚠️  Skipped: Terms of Service - already exists (ID: {existing.id})"
            )
        else:
            try:
                terms = content_page_service.create_page(
                    db,
                    slug="terms",
                    title="Terms of Service",
                    content="""
                    <p><em>Last updated: January 1, 2024</em></p>

                    <h2>1. Acceptance of Terms</h2>
                    <p>
                        By accessing and using this marketplace platform, you accept and agree to be
                        bound by the terms and provisions of this agreement.
                    </p>

                    <h2>2. Use License</h2>
                    <p>
                        Permission is granted to temporarily access the materials on our platform for
                        personal, non-commercial transitory viewing only.
                    </p>

                    <h2>3. Account Terms</h2>
                    <ul>
                        <li>You must be at least 18 years old to use our platform</li>
                        <li>You must provide accurate and complete registration information</li>
                        <li>You are responsible for maintaining the security of your account</li>
                        <li>You are responsible for all activities under your account</li>
                    </ul>

                    <h2>4. Vendor Responsibilities</h2>
                    <ul>
                        <li>Provide accurate product information and pricing</li>
                        <li>Honor all orders and commitments made through the platform</li>
                        <li>Comply with all applicable laws and regulations</li>
                        <li>Maintain appropriate customer service standards</li>
                    </ul>

                    <h2>5. Prohibited Activities</h2>
                    <p>You may not use our platform to:</p>
                    <ul>
                        <li>Engage in any fraudulent or illegal activities</li>
                        <li>Violate any intellectual property rights</li>
                        <li>Transmit harmful code or malware</li>
                        <li>Interfere with platform operations</li>
                    </ul>

                    <h2>6. Termination</h2>
                    <p>
                        We reserve the right to terminate or suspend your account at any time for
                        violation of these terms.
                    </p>

                    <h2>7. Limitation of Liability</h2>
                    <p>
                        In no event shall our company be liable for any damages arising out of the
                        use or inability to use our platform.
                    </p>

                    <h2>8. Changes to Terms</h2>
                    <p>
                        We reserve the right to modify these terms at any time. We will notify users
                        of any changes via email.
                    </p>

                    <h2>9. Contact</h2>
                    <p>
                        If you have any questions about these Terms, please contact us at
                        <a href="mailto:legal@marketplace.com">legal@marketplace.com</a>.
                    </p>
                """,
                    vendor_id=None,
                    is_published=True,
                    show_in_header=False,  # Too legal for header
                    show_in_footer=True,  # Show in footer
                    display_order=10,
                    meta_description="Read our terms of service and platform usage policies.",
                    meta_keywords="terms of service, terms, legal, policy, agreement",
                )
                print(f"   ✅ Created: {terms.title} (/{terms.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: Terms of Service - {str(e)}")

        # ========================================================================
        # 6. PRIVACY POLICY
        # ========================================================================
        print("6. Creating Privacy Policy page...")

        existing = (
            db.query(ContentPage).filter_by(vendor_id=None, slug="privacy").first()
        )
        if existing:
            print(f"   ⚠️  Skipped: Privacy Policy - already exists (ID: {existing.id})")
        else:
            try:
                privacy = content_page_service.create_page(
                    db,
                    slug="privacy",
                    title="Privacy Policy",
                    content="""
                    <p><em>Last updated: January 1, 2024</em></p>

                    <h2>1. Information We Collect</h2>
                    <p>We collect information you provide directly to us, including:</p>
                    <ul>
                        <li>Name, email address, and contact information</li>
                        <li>Payment and billing information</li>
                        <li>Store and product information</li>
                        <li>Communications with us</li>
                    </ul>

                    <h2>2. How We Use Your Information</h2>
                    <p>We use the information we collect to:</p>
                    <ul>
                        <li>Provide, maintain, and improve our services</li>
                        <li>Process transactions and send related information</li>
                        <li>Send technical notices and support messages</li>
                        <li>Respond to your comments and questions</li>
                        <li>Monitor and analyze trends and usage</li>
                    </ul>

                    <h2>3. Information Sharing</h2>
                    <p>
                        We do not sell your personal information. We may share information with:
                    </p>
                    <ul>
                        <li>Service providers who help us operate our platform</li>
                        <li>Law enforcement when required by law</li>
                        <li>Other parties with your consent</li>
                    </ul>

                    <h2>4. Data Security</h2>
                    <p>
                        We implement appropriate security measures to protect your personal information.
                        However, no method of transmission over the internet is 100% secure.
                    </p>

                    <h2>5. Your Rights</h2>
                    <p>You have the right to:</p>
                    <ul>
                        <li>Access your personal information</li>
                        <li>Correct inaccurate information</li>
                        <li>Request deletion of your information</li>
                        <li>Opt-out of marketing communications</li>
                    </ul>

                    <h2>6. Cookies</h2>
                    <p>
                        We use cookies and similar tracking technologies to track activity on our
                        platform and hold certain information. You can instruct your browser to
                        refuse cookies.
                    </p>

                    <h2>7. Changes to This Policy</h2>
                    <p>
                        We may update this privacy policy from time to time. We will notify you of
                        any changes by posting the new policy on this page.
                    </p>

                    <h2>8. Contact Us</h2>
                    <p>
                        If you have questions about this Privacy Policy, please contact us at
                        <a href="mailto:privacy@marketplace.com">privacy@marketplace.com</a>.
                    </p>
                """,
                    vendor_id=None,
                    is_published=True,
                    show_in_header=False,  # Too legal for header
                    show_in_footer=True,  # Show in footer
                    display_order=11,
                    meta_description="Learn how we collect, use, and protect your personal information.",
                    meta_keywords="privacy policy, privacy, data protection, gdpr, personal information",
                )
                print(f"   ✅ Created: {privacy.title} (/{privacy.slug})")
            except Exception as e:
                print(f"   ⚠️  Error: Privacy Policy - {str(e)}")

        print()
        print("=" * 80)
        print("✅ Platform pages creation completed successfully!")
        print("=" * 80)
        print()
        print("Created pages:")
        print("  - Platform Homepage: http://localhost:8000/")
        print("  - About Us:          http://localhost:8000/about")
        print("  - FAQ:               http://localhost:8000/faq")
        print("  - Contact Us:        http://localhost:8000/contact")
        print("  - Terms of Service:  http://localhost:8000/terms")
        print("  - Privacy Policy:    http://localhost:8000/privacy")
        print()

    except Exception as e:
        print(f"\n❌ Error: {e}")
        db.rollback()
        raise
    finally:
        db.close()


if __name__ == "__main__":
    create_platform_pages()
