#!/usr/bin/env python3
"""
Database initialization script.
Creates tables and seeds initial data.

Usage:
    python3 init_db.py
"""

import os
import sys
from app import create_app, bcrypt
from app.models import db, Product, User

# Add the parent directory to the path
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

def init_database():
    """Initialize the database with tables and sample data."""
    app = create_app()
    
    with app.app_context():
        # Create all tables
        print("Creating database tables...")
        db.create_all()
        print("✓ Database tables created")
        
        # Check if products already exist
        if Product.query.first() is None:
            print("\nSeeding initial products...")
            
            products_data = [
                {
                    "name": "Organic Moringa Powder",
                    "price": 4000.00,
                    "image_url": "/static/images/701ed985f9328736.jpg",
                    "badge": "Bestseller",
                    "description": "Premium organic moringa powder rich in vitamins and minerals",
                    "quantity_available": 50
                },
                {
                    "name": "Golden Turmeric Blend",
                    "price": 3000.00,
                    "image_url": "/static/images/701ed985f9328736.jpg",
                    "badge": "Popular",
                    "description": "Pure turmeric powder with black pepper for enhanced absorption",
                    "quantity_available": 75
                },
                {
                    "name": "Ashwagandha Root",
                    "price": 4500.00,
                    "image_url": "/static/images/701ed985f9328736.jpg",
                    "badge": None,
                    "description": "Ayurvedic adaptogenic herb for stress relief and energy",
                    "quantity_available": 60
                },
                {
                    "name": "Organic Ginger Root",
                    "price": 2500.00,
                    "image_url": "/static/images/701ed985f9328736.jpg",
                    "badge": "New",
                    "description": "Fresh organic ginger root for digestion and immune support",
                    "quantity_available": 40
                },
                {
                    "name": "Neem Leaf Powder",
                    "price": 3500.00,
                    "image_url": "/static/images/701ed985f9328736.jpg",
                    "badge": "Popular",
                    "description": "Natural neem leaf powder for detoxification and skin health",
                    "quantity_available": 35
                },
            ]
            
            for product_data in products_data:
                product = Product(**product_data)
                db.session.add(product)
                print(f"  ✓ Added: {product.name}")
            
            db.session.commit()
            print("✓ Products seeded successfully\n")
        else:
            print("✓ Products already exist in database")
        
        # Create admin user if it doesn't exist
        admin_email = "admin@prochoice.com"
        admin_user = User.query.filter_by(email=admin_email).first()
        
        if not admin_user:
            print("\nCreating admin user...")
            password_hash = bcrypt.generate_password_hash("admin123").decode('utf-8')
            admin_user = User(
                full_name="Admin",
                email=admin_email,
                password_hash=password_hash,
                is_admin=True
            )
            db.session.add(admin_user)
            db.session.commit()
            print(f"✓ Admin user created")
            print(f"  Email: {admin_email}")
            print(f"  Password: admin123")
            print(f"  ⚠️  Please change the password after first login!\n")
        else:
            print("✓ Admin user already exists")

if __name__ == '__main__':
    try:
        init_database()
        print("Database initialization complete!")
    except Exception as e:
        print(f"✗ Error initializing database: {e}")
        sys.exit(1)
