# debug_db.py
import sqlite3
import os

def check_database():
    print("🔍 DATABASE DEBUG CHECK")
    print("=" * 40)
    
    # Check current directory
    print(f"📁 Current directory: {os.getcwd()}")
    print(f"📁 Database file exists: {os.path.exists('jokes.db')}")
    
    if not os.path.exists('jokes.db'):
        print("❌ ERROR: jokes.db file not found in current directory!")
        print("💡 Try running: python3 database.py first")
        return
    
    try:
        # Connect to database
        conn = sqlite3.connect('jokes.db')
        cursor = conn.cursor()
        
        print("✅ Connected to database successfully")
        
        # Check what tables exist
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = cursor.fetchall()
        print(f"\n📋 Tables found: {[table[0] for table in tables]}")
        
        if 'jokes' not in [table[0] for table in tables]:
            print("❌ ERROR: 'jokes' table not found!")
            print("💡 Try running: python3 database.py to create the table")
            conn.close()
            return
        
        # Check number of jokes
        cursor.execute("SELECT COUNT(*) FROM jokes")
        count = cursor.fetchone()[0]
        print(f"📊 Total jokes in database: {count}")
        
        if count == 0:
            print("⚠️  WARNING: Database is empty!")
            print("💡 Load sample data with: sqlite3 jokes.db < sample_data.sql")
        else:
            # Show some sample data
            print("\n🔍 Sample jokes (first 3):")
            print("-" * 50)
            cursor.execute("SELECT id, joke, contributor, sentiment_label FROM jokes LIMIT 3")
            jokes = cursor.fetchall()
            
            for joke in jokes:
                print(f"\nID: {joke[0]}")
                print(f"Joke: {joke[1]}")
                print(f"Contributor: {joke[2]}")
                print(f"Mood: {joke[3]}")
                print("-" * 30)
        
        # Check column names
        print("\n📝 Table structure:")
        cursor.execute("PRAGMA table_info(jokes)")
        columns = cursor.fetchall()
        for col in columns:
            print(f"  {col[1]} ({col[2]})")
        
        conn.close()
        print("\n✅ Debug check completed!")
        
    except sqlite3.Error as e:
        print(f"❌ SQLite error: {e}")
    except Exception as e:
        print(f"❌ General error: {e}")

if __name__ == "__main__":
    check_database()