"""
Blog Application Example

Demonstrates a simple blog with posts, authors, and comments using VibeDB.
"""

from datetime import datetime
from vibedb import VibeDB, Q


def main():
    print("📝 VibeDB Blog Application Example\n")

    # Create database
    db = VibeDB("blog.db")

    # Get collections
    authors = db.collection("authors")
    posts = db.collection("posts")
    comments = db.collection("comments")

    # Clear existing data for demo
    authors.delete_many({})
    posts.delete_many({})
    comments.delete_many({})

    print("1️⃣  Setting up schemas...\n")

    # Optional schemas for data validation
    authors.set_schema({
        "name": {"type": "string", "required": True, "min": 1},
        "email": {"type": "string", "required": True, "unique": True},
        "bio": {"type": "string"},
        "role": {"type": "string", "enum": ["admin", "editor", "author"], "default": "author"},
    })

    posts.set_schema({
        "title": {"type": "string", "required": True, "min": 1, "max": 200},
        "content": {"type": "string", "required": True},
        "author_id": {"type": "string", "required": True},
        "tags": {"type": "array", "items": {"type": "string"}},
        "status": {"type": "string", "enum": ["draft", "published", "archived"], "default": "draft"},
        "views": {"type": "integer", "min": 0, "default": 0},
    })

    comments.set_schema({
        "post_id": {"type": "string", "required": True},
        "author_name": {"type": "string", "required": True},
        "content": {"type": "string", "required": True},
        "approved": {"type": "boolean", "default": False},
    })

    print("2️⃣  Creating authors...\n")

    # Create authors
    alice_id = authors.insert({
        "name": "Alice Johnson",
        "email": "alice@blog.com",
        "bio": "Tech writer and Python enthusiast",
        "role": "admin"
    })
    print(f"  ✓ Created author: Alice Johnson ({alice_id[:8]}...)")

    bob_id = authors.insert({
        "name": "Bob Smith",
        "email": "bob@blog.com",
        "bio": "Web developer and blogger",
        "role": "author"
    })
    print(f"  ✓ Created author: Bob Smith ({bob_id[:8]}...)")

    print("\n3️⃣  Creating blog posts...\n")

    # Create posts
    post1_id = posts.insert({
        "title": "Getting Started with VibeDB",
        "content": "VibeDB is a document database built on SQLite...",
        "author_id": alice_id,
        "tags": ["python", "database", "tutorial"],
        "status": "published",
        "views": 150
    })
    print(f"  ✓ Published: {posts.get(post1_id).title}")

    post2_id = posts.insert({
        "title": "Advanced Query Techniques",
        "content": "Learn how to write complex queries using Q builder...",
        "author_id": alice_id,
        "tags": ["python", "advanced", "queries"],
        "status": "published",
        "views": 89
    })
    print(f"  ✓ Published: {posts.get(post2_id).title}")

    post3_id = posts.insert({
        "title": "Building Web Apps with Flask",
        "content": "Flask is a micro web framework for Python...",
        "author_id": bob_id,
        "tags": ["python", "flask", "web"],
        "status": "published",
        "views": 234
    })
    print(f"  ✓ Published: {posts.get(post3_id).title}")

    post4_id = posts.insert({
        "title": "Draft: Schema Validation Guide",
        "content": "This post is still being written...",
        "author_id": alice_id,
        "tags": ["python", "schema"],
        "status": "draft",
        "views": 0
    })
    print(f"  ✓ Draft saved: {posts.get(post4_id).title}")

    print("\n4️⃣  Adding comments...\n")

    # Add comments
    comments.insert({
        "post_id": post1_id,
        "author_name": "Charlie",
        "content": "Great tutorial! Very helpful.",
        "approved": True
    })

    comments.insert({
        "post_id": post1_id,
        "author_name": "Diana",
        "content": "Thanks for sharing this!",
        "approved": True
    })

    comments.insert({
        "post_id": post3_id,
        "author_name": "Eve",
        "content": "Awesome Flask guide!",
        "approved": True
    })

    comments.insert({
        "post_id": post3_id,
        "author_name": "Spammer",
        "content": "Buy my product!!!",
        "approved": False  # Not approved
    })

    print(f"  ✓ Added {comments.count()} comments")

    print("\n5️⃣  Creating indexes for performance...\n")

    # Create indexes for common queries
    posts.create_index(["author_id"])
    posts.create_index(["status"])
    posts.create_index(["views"])
    comments.create_index(["post_id"])
    authors.create_index(["email"], unique=True)

    print("  ✓ Created indexes on posts.author_id, posts.status, posts.views")
    print("  ✓ Created indexes on comments.post_id, authors.email")

    print("\n6️⃣  Running queries...\n")

    # Query: Get all published posts
    published = posts.find(Q.eq("status", "published")).to_list()
    print(f"  📰 Published posts: {len(published)}")

    # Query: Get posts by Alice
    alice_posts = posts.find(Q.eq("author_id", alice_id)).to_list()
    print(f"  ✍️  Alice's posts: {len(alice_posts)}")

    # Query: Get popular posts (views > 100)
    popular = posts.find(Q.gt("views", 100)).sort("views", -1).to_list()
    print(f"  🔥 Popular posts (>100 views):")
    for post in popular:
        author = authors.get(post.author_id)
        print(f"     • {post.title} by {author.name} ({post.views} views)")

    # Query: Get posts with specific tag
    python_posts = posts.find(Q.has("tags", "python")).to_list()
    print(f"\n  🐍 Posts tagged 'python': {len(python_posts)}")

    # Query: Get approved comments for a post
    post1_comments = comments.find({
        "post_id": post1_id,
        "approved": True
    }).to_list()
    print(f"\n  💬 Approved comments on '{posts.get(post1_id).title}':")
    for comment in post1_comments:
        print(f"     • {comment.author_name}: {comment.content}")

    # Complex query: Published posts by Alice with >50 views
    alice_popular = posts.find(
        Q.eq("author_id", alice_id) &
        Q.eq("status", "published") &
        Q.gt("views", 50)
    ).to_list()
    print(f"\n  ⭐ Alice's popular published posts: {len(alice_popular)}")

    print("\n7️⃣  Updating data...\n")

    # Increment view count
    post1 = posts.get(post1_id)
    posts.update(post1_id, {"views": post1.views + 1})
    print(f"  ✓ Incremented views on '{post1.title}': {post1.views} → {post1.views + 1}")

    # Publish draft
    posts.update(post4_id, {"status": "published"})
    print(f"  ✓ Published draft post: {posts.get(post4_id).title}")

    # Delete spam comment
    spam_comment = comments.find_one({"author_name": "Spammer"})
    comments.delete(spam_comment["_id"])
    print(f"  ✓ Deleted spam comment")

    print("\n8️⃣  Database statistics...\n")

    stats = db.stats()
    print(f"  📊 Collections: {stats['collection_count']}")
    print(f"  📄 Total documents: {stats['total_documents']}")
    print(f"  💾 Database size: {stats.get('size_mb', 0):.2f} MB")

    print(f"\n  Authors: {authors.count()}")
    print(f"  Posts: {posts.count()} ({posts.count(Q.eq('status', 'published'))} published)")
    print(f"  Comments: {comments.count()} ({comments.count(Q.eq('approved', True))} approved)")

    print("\n9️⃣  Index suggestions...\n")

    # Run some queries to generate suggestions
    for _ in range(10):
        posts.find({"status": "published", "views": {"$gte": 100}}).to_list()

    suggestions = posts.index_suggestions()
    if suggestions:
        print("  💡 Index suggestions:")
        for suggestion in suggestions[:3]:  # Show top 3
            print(f"     • Fields: {suggestion['fields']}")
            print(f"       Reason: {suggestion['reason']}")
    else:
        print("  ✓ No index suggestions (queries are fast!)")

    print("\n✅ Blog application demo complete!")
    print(f"\n💡 Try launching Studio UI: db.studio()")

    db.close()


if __name__ == "__main__":
    main()
