# jokes_v4.py
import sqlite3
import random
from datetime import datetime
from textblob import TextBlob  # Simple NLP library

def analyze_joke_sentiment(joke_text):
    """Use AI to analyze the sentiment of a joke"""
    analysis = TextBlob(joke_text)
    polarity = analysis.sentiment.polarity
    
    if polarity > 0.1:
        label = "😊 Positive"
    elif polarity < -0.1:
        label = "😒 Negative"
    else:
        label = "😐 Neutral"
    
    return polarity, label

def get_user_sentiment_for_joke(db, joke_id):
    """Get the average user sentiment for a specific joke"""
    cursor = db.execute('''
        SELECT 
            CASE 
                WHEN AVG(CASE WHEN user_sentiment = 'up' THEN 1 
                             WHEN user_sentiment = 'down' THEN -1 
                             ELSE 0 END) > 0.1 THEN '👍 Up'
                WHEN AVG(CASE WHEN user_sentiment = 'up' THEN 1 
                             WHEN user_sentiment = 'down' THEN -1 
                             ELSE 0 END) < -0.1 THEN '👎 Down'
                ELSE '😐 Neutral'
            END as avg_sentiment,
            COUNT(*) as total_votes
        FROM user_sentiments 
        WHERE joke_id = ?
    ''', (joke_id,))
    
    result = cursor.fetchone()
    avg_sentiment, total_votes = result
    return avg_sentiment, total_votes

def add_user_sentiment(db, joke_id, user_choice):
    """Add user sentiment for a specific joke"""
    try:
        db.execute('''
            INSERT INTO user_sentiments (joke_id, user_sentiment) 
            VALUES (?, ?)
        ''', (joke_id, user_choice))
        db.commit()
        return True
    except Exception as e:
        print(f"❌ Error saving sentiment: {e}")
        return False

def main():
    db = sqlite3.connect('jokes.db')
    
    while True:
        print("\n" + "="*30)
        print("🤖 AI-ENHANCED JOKE BOT 🤖")
        print("="*30)
        print("1. Get random joke")
        print("2. Add new joke")
        print("3. Analyze joke sentiment")
        print("4. Get joke by mood")
        print("5. View all jokes with sentiment")
        print("6. Quit")
        
        choice = input("\nYour choice: ").strip()
        
        if choice == "1":
            # Get random joke with sentiment info
            cursor = db.execute('''
                SELECT id, joke, contributor, published, sentiment_label 
                FROM jokes 
                ORDER BY RANDOM() 
                LIMIT 1
            ''')
            joke_data = cursor.fetchone()
            
            if joke_data:
                joke_id, joke, contributor, published, sentiment = joke_data
                print(f"\n🤣 {joke}")
                print(f"   👤 Contributor: {contributor}")
                print(f"   📅 Published: {published}")
                print(f"   🧠 AI Mood Analysis: {sentiment}")
                
                # Get and display user sentiment stats
                avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
                if total_votes > 0:
                    print(f"   👥 Community Rating: {avg_sentiment} ({total_votes} votes)")
                
                # Ask user for their sentiment
                print(f"\n🎯 Rate this joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
                user_input = input("Your choice (u/d/n): ").strip().lower()
                
                if user_input in ['u', 'up']:
                    user_choice = 'up'
                elif user_input in ['d', 'down']:
                    user_choice = 'down'
                else:
                    user_choice = 'neutral'
                
                if add_user_sentiment(db, joke_id, user_choice):
                    print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
                else:
                    print("❌ Could not save your rating.")
            else:
                print("📭 No jokes in the database yet!")
        
        elif choice == "2":
            new_joke = input("Enter your joke: ").strip()
            if not new_joke:
                print("❌ Joke cannot be empty!")
                continue
                
            name = input("Your name (or press Enter for 'Anonymous'): ").strip() or "Anonymous"
            
            # AI Analysis
            score, label = analyze_joke_sentiment(new_joke)
            print(f"\n🤖 AI Analysis Results:")
            print(f"   Sentiment Score: {score:.2f}")
            print(f"   Mood Label: {label}")
            
            # Get current date/time
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            try:
                cursor = db.cursor()
                cursor.execute('''
                    INSERT INTO jokes (joke, contributor, published, sentiment_score, sentiment_label) 
                    VALUES (?, ?, ?, ?, ?)
                ''', (new_joke, name, current_time, score, label))
                
                # Get the ID of the newly inserted joke
                new_joke_id = cursor.lastrowid
                
                db.commit()
                print("✅ Joke saved with AI analysis!")
                
                # Ask user for their sentiment on the new joke
                print(f"\n🎯 Rate your own joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
                user_input = input("Your choice (u/d/n): ").strip().lower()
                
                if user_input in ['u', 'up']:
                    user_choice = 'up'
                elif user_input in ['d', 'down']:
                    user_choice = 'down'
                else:
                    user_choice = 'neutral'
                
                if add_user_sentiment(db, new_joke_id, user_choice):
                    print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
            except Exception as e:
                print(f"❌ Error saving joke: {e}")
        
        elif choice == "3":
            joke_text = input("Enter a joke to analyze: ").strip()
            if joke_text:
                score, label = analyze_joke_sentiment(joke_text)
                print(f"\n📊 AI Analysis Results:")
                print(f"   Joke: '{joke_text}'")
                print(f"   Sentiment Score: {score:.2f}")
                print(f"   Mood Label: {label}")
                
                # Interpretation
                print(f"\n📈 Interpretation:")
                if score > 0.5:
                    print("   Very positive joke! 😄")
                elif score > 0.1:
                    print("   Positive joke! 😊")
                elif score < -0.5:
                    print("   Very negative/sarcastic joke! 😠")
                elif score < -0.1:
                    print("   Negative joke! 😒")
                else:
                    print("   Neutral joke! 😐")
            else:
                print("❌ Please enter a joke to analyze.")
        
        elif choice == "4":
            print("\n🎭 Choose mood:")
            print("1. 😊 Positive jokes")
            print("2. 😒 Negative jokes")
            print("3. 😐 Neutral jokes")
            print("4. 😄 Very positive jokes (score > 0.5)")
            print("5. 😠 Very negative jokes (score < -0.5)")
            
            mood_choice = input("Your choice: ").strip()
            
            mood_queries = {
                "1": ("😊 Positive", "sentiment_label = '😊 Positive'"),
                "2": ("😒 Negative", "sentiment_label = '😒 Negative'"),
                "3": ("😐 Neutral", "sentiment_label = '😐 Neutral'"),
                "4": ("😄 Very Positive", "sentiment_score > 0.5"),
                "5": ("😠 Very Negative", "sentiment_score < -0.5")
            }
            
            if mood_choice in mood_queries:
                mood_name, query = mood_queries[mood_choice]
                
                cursor = db.execute(f'''
                    SELECT id, joke, contributor, sentiment_score 
                    FROM jokes 
                    WHERE {query}
                    ORDER BY RANDOM() 
                    LIMIT 1
                ''')
                
                joke_data = cursor.fetchone()
                
                if joke_data:
                    joke_id, joke, contributor, score = joke_data
                    print(f"\n{mood_name} joke:")
                    print(f"🤣 {joke}")
                    print(f"   👤 Contributor: {contributor}")
                    print(f"   📊 Sentiment Score: {score:.2f}")
                    
                    # Get and display user sentiment stats
                    avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
                    if total_votes > 0:
                        print(f"   👥 Community Rating: {avg_sentiment} ({total_votes} votes)")
                    
                    # Ask user for their sentiment
                    print(f"\n🎯 Rate this joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
                    user_input = input("Your choice (u/d/n): ").strip().lower()
                    
                    if user_input in ['u', 'up']:
                        user_choice = 'up'
                    elif user_input in ['d', 'down']:
                        user_choice = 'down'
                    else:
                        user_choice = 'neutral'
                    
                    if add_user_sentiment(db, joke_id, user_choice):
                        print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
                else:
                    print(f"📭 No {mood_name.lower()} jokes yet!")
            else:
                print("❌ Invalid choice!")
        
        elif choice == "5":
            print("\n📋 ALL JOKES IN DATABASE:")
            print("-" * 70)
            
            cursor = db.execute('''
                SELECT j.id, j.joke, j.contributor, j.sentiment_label, j.sentiment_score 
                FROM jokes j
                ORDER BY j.id DESC
            ''')
            
            jokes = cursor.fetchall()
            
            if jokes:
                for i, (joke_id, joke, contributor, label, score) in enumerate(jokes, 1):
                    print(f"\n{i}. {joke}")
                    print(f"   👤 {contributor} | AI: {label} | Score: {score:.2f}")
                    
                    # Get and display user sentiment stats
                    avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
                    if total_votes > 0:
                        print(f"   👥 Community Rating: {avg_sentiment} ({total_votes} votes)")
                        
                print(f"\n📊 Total jokes: {len(jokes)}")
            else:
                print("📭 No jokes in the database yet!")
        
        elif choice == "6":
            print("\n👋 Goodbye! Thanks for using the AI Joke Bot!")
            break
        
        else:
            print("❌ Invalid choice. Please select 1-6.")

    db.close()

if __name__ == "__main__":
    # Check if textblob is installed
    try:
        import textblob
        main()
    except ImportError:
        print("❌ ERROR: textblob library is not installed!")
        print("\n📦 Please install it using:")
        print("   pip install textblob")
        print("   python -m textblob.download_corpora")
        print("\nThen run this script again.")