#!/usr/bin/env python3
"""
Setup script to properly initialize the database following the project specification.
This ensures the database has the correct schema and sample data.
"""

import os
import sqlite3
import subprocess
import sys

def setup_database():
    db_path = 'jokes.db'
    
    print("🚀 Starting database setup process...")
    
    # Step 1: Remove existing database file if it exists
    if os.path.exists(db_path):
        print(f"🗑️  Removing existing database: {db_path}")
        os.remove(db_path)
        print("✅ Old database removed")
    else:
        print("📋 No existing database to remove")
    
    # Step 2: Create database with correct schema
    print("\n🔧 Creating database with correct schema...")
    result = subprocess.run([sys.executable, 'database.py'], capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ Error creating database: {result.stderr}")
        return False
    else:
        print("✅ Database schema created successfully")
    
    # Step 3: Populate database with sample data
    print("\n📚 Populating database with sample data...")
    result = subprocess.run([sys.executable, 'populate_db.py'], capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ Error populating database: {result.stderr}")
        return False
    else:
        print("✅ Database populated with sample data")
    
    # Step 4: Verify the database
    print("\n🔍 Verifying database setup...")
    result = subprocess.run([sys.executable, 'check_db.py'], capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ Error verifying database: {result.stderr}")
        return False
    else:
        print("✅ Database verified successfully")
        print(result.stdout)
    
    print("\n🎉 Database setup completed successfully!")
    print("You can now run 'python jokes.py' to start the Joke Bot.")
    
    return True

if __name__ == '__main__':
    success = setup_database()
    if not success:
        print("\n💥 Database setup failed. Please check the errors above.")
        sys.exit(1)