#!/usr/bin/env python3
"""
Create Landing Page for Store

This script creates a landing page for a store with the specified template.
Usage: python scripts/create_landing_page.py
"""

import sys
from pathlib import Path

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

from datetime import UTC, datetime

from sqlalchemy.orm import Session

from app.core.database import SessionLocal
from app.modules.cms.models import ContentPage
from app.modules.tenancy.models import Store


def create_landing_page(
    store_subdomain: str,
    template: str = "default",
    title: str = None,
    content: str = None,
):
    """
    Create a landing page for a store.

    Args:
        store_subdomain: Store subdomain (e.g., 'orion')
        template: Template to use (default, minimal, modern, full)
        title: Page title (defaults to store name)
        content: HTML content (optional)
    """
    db: Session = SessionLocal()

    try:
        # Find store
        store = db.query(Store).filter(Store.subdomain == store_subdomain).first()

        if not store:
            print(f"❌ Store '{store_subdomain}' not found!")
            return False

        print(f"✅ Found store: {store.name} (ID: {store.id})")

        # Check if landing page already exists
        existing = (
            db.query(ContentPage)
            .filter(ContentPage.store_id == store.id, ContentPage.slug == "landing")
            .first()
        )

        if existing:
            print(f"⚠️  Landing page already exists (ID: {existing.id})")
            print(f"   Current template: {existing.template}")

            # Update it
            existing.template = template
            existing.title = title or existing.title
            if content:
                existing.content = content
            existing.is_published = True
            existing.updated_at = datetime.now(UTC)

            db.commit()
            print(f"✅ Updated landing page with template: {template}")
        else:
            # Create new landing page
            landing_page = ContentPage(
                store_id=store.id,
                slug="landing",
                title=title or f"Welcome to {store.name}",
                content=content
                or f"""
                    <h2>About {store.name}</h2>
                    <p>{store.description or "Your trusted shopping destination for quality products."}</p>

                    <h3>Why Choose Us?</h3>
                    <ul>
                        <li><strong>Quality Products:</strong> Carefully curated selection</li>
                        <li><strong>Fast Shipping:</strong> Quick delivery to your door</li>
                        <li><strong>Great Service:</strong> Customer satisfaction guaranteed</li>
                    </ul>

                    <h3>Our Story</h3>
                    <p>We've been serving customers since 2020, providing exceptional products and service.
                    Our mission is to make online shopping easy, enjoyable, and reliable.</p>
                """,
                content_format="html",
                template=template,
                meta_description=f"Shop at {store.name} for quality products and great service",
                is_published=True,
                published_at=datetime.now(UTC),
                show_in_footer=False,
                show_in_header=False,
                display_order=0,
            )

            db.add(landing_page)
            db.commit()
            db.refresh(landing_page)

            print(f"✅ Created landing page (ID: {landing_page.id})")
            print(f"   Template: {template}")
            print(f"   Title: {landing_page.title}")

        # Print access URLs
        print("\n📍 Access your landing page at:")
        print(f"   Path-based: http://localhost:8000/stores/{store.subdomain}/")
        print(f"   Shop page:  http://localhost:8000/stores/{store.subdomain}/shop/")

        return True

    except Exception as e:
        print(f"❌ Error: {e}")
        db.rollback()
        return False
    finally:
        db.close()


def list_stores():
    """List all stores in the system."""
    db: Session = SessionLocal()

    try:
        stores = db.query(Store).filter(Store.is_active == True).all()

        if not stores:
            print("❌ No active stores found!")
            return

        print("\n📋 Active Stores:")
        print("=" * 60)
        for store in stores:
            print(f"  • {store.name}")
            print(f"    Subdomain: {store.subdomain}")
            print(f"    Code: {store.store_code}")

            # Check if has landing page
            landing = (
                db.query(ContentPage)
                .filter(
                    ContentPage.store_id == store.id, ContentPage.slug == "landing"
                )
                .first()
            )

            if landing:
                print(f"    Landing Page: ✅ ({landing.template})")
            else:
                print("    Landing Page: ❌ None")
            print()

    finally:
        db.close()


def show_templates():
    """Show available templates."""
    print("\n🎨 Available Templates:")
    print("=" * 60)

    templates = [
        ("default", "Clean professional layout with 3-column quick links"),
        ("minimal", "Ultra-simple centered design with single CTA"),
        ("modern", "Full-screen hero with animations and features"),
        ("full", "Maximum features with split-screen hero and stats"),
    ]

    for name, desc in templates:
        print(f"  • {name:<10} - {desc}")
    print()


if __name__ == "__main__":
    print("\n" + "=" * 60)
    print("  STORE LANDING PAGE CREATOR")
    print("=" * 60)

    # List stores
    list_stores()

    # Show templates
    show_templates()

    # Interactive creation
    print("📝 Create Landing Page")
    print("-" * 60)

    store_subdomain = input("Enter store subdomain (e.g., orion): ").strip()

    if not store_subdomain:
        print("❌ Store subdomain is required!")
        sys.exit(1)

    print("\nAvailable templates: default, minimal, modern, full")
    template = input("Enter template (default): ").strip() or "default"

    if template not in ["default", "minimal", "modern", "full"]:
        print(f"⚠️  Invalid template '{template}', using 'default'")
        template = "default"

    title = input("Enter page title (optional, press Enter to use default): ").strip()

    print("\n🚀 Creating landing page...")
    print("-" * 60)

    success = create_landing_page(
        store_subdomain=store_subdomain,
        template=template,
        title=title if title else None,
    )

    if success:
        print("\n✅ SUCCESS! Landing page is ready.")
        print("\n💡 Try different templates:")
        print("   python scripts/create_landing_page.py")
        print("   # Then choose: minimal, modern, or full")
    else:
        print("\n❌ Failed to create landing page")
        sys.exit(1)
