import mysql.connector
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from datetime import datetime
import sys

def compute_all_recommendations():
    """Pre-compute AI recommendations for ALL books and store in database"""
    db = None
    try:
        print(f"[{datetime.now()}] Connecting to database...")
        
        # 1. Database Connection
        db = mysql.connector.connect(
            host="localhost",
            user="wilcobbh_wilcodb",
            password="3TiQ{@xwqwcu",
            database="wilcobbh_wilco"
        )
        cursor = db.cursor()
        
        print(f"[{datetime.now()}] Starting recommendation computation...")
        
        # 2. Load purchase data - only completed orders
        query = """
        SELECT 
            orders.user_id, 
            orderproducts.mbooktypeid as book_id 
        FROM orders 
        LEFT JOIN orderproducts ON orders.order_id = orderproducts.order_id 
        WHERE orders.order_status_id = 1 
          AND orderproducts.mbooktypeid IS NOT NULL
        ORDER BY orders.order_id DESC 
        LIMIT 50000
        """
        
        print(f"[{datetime.now()}] Loading order data...")
        df = pd.read_sql(query, db)
        
        if df.empty:
            print("❌ No data found!")
            return
        
        print(f"[{datetime.now()}] Loaded {len(df)} order records")
        
        # 3. Clean data
        print(f"[{datetime.now()}] Cleaning data...")
        df['book_id'] = pd.to_numeric(df['book_id'], errors='coerce')
        df['user_id'] = pd.to_numeric(df['user_id'], errors='coerce')
        df = df.dropna().drop_duplicates()
        
        print(f"[{datetime.now()}] After cleaning: {len(df)} records")
        
        # 4. Filter books with at least 2 purchases (reduced threshold for more coverage)
        book_counts = df['book_id'].value_counts()
        valid_books = book_counts[book_counts >= 2].index
        df = df[df['book_id'].isin(valid_books)]
        
        if df.empty:
            print("❌ No valid books found after filtering!")
            return
        
        print(f"[{datetime.now()}] Processing {len(valid_books)} books with sufficient data...")
        
        # 5. Create user-item matrix
        print(f"[{datetime.now()}] Creating user-item matrix...")
        df['bought'] = 1
        matrix = df.pivot_table(
            index='book_id',
            columns='user_id',
            values='bought',
            fill_value=0
        )
        
        print(f"[{datetime.now()}] Matrix shape: {matrix.shape[0]} books x {matrix.shape[1]} users")
        
        # 6. Compute similarity matrix
        print(f"[{datetime.now()}] Computing cosine similarities (this may take a few minutes)...")
        similarity_matrix = cosine_similarity(matrix)
        sim_df = pd.DataFrame(
            similarity_matrix,
            index=matrix.index,
            columns=matrix.index
        )
        
        print(f"[{datetime.now()}] Similarity computation complete!")
        
        # 7. Clear old recommendations
        print(f"[{datetime.now()}] Clearing old recommendations...")
        cursor.execute("TRUNCATE TABLE book_recommendations")
        db.commit()
        
        # 8. Store top 10 recommendations for each book
        insert_query = """
        INSERT INTO book_recommendations 
        (book_id, recommended_book_id, similarity_score, rank_position, created_at, updated_at) 
        VALUES (%s, %s, %s, %s, NOW(), NOW())
        """
        
        print(f"[{datetime.now()}] Storing recommendations in database...")
        batch_data = []
        books_processed = 0
        
        for book_id in sim_df.index:
            # Get top 10 similar books (excluding self)
            similar_books = sim_df[book_id].sort_values(ascending=False)[1:11]
            
            for rank, (rec_book_id, score) in enumerate(similar_books.items(), 1):
                if score > 0:  # Only store positive similarities
                    batch_data.append((
                        int(book_id),
                        int(rec_book_id),
                        float(score),
                        rank
                    ))
            
            books_processed += 1
            
            # Batch insert every 1000 records for efficiency
            if len(batch_data) >= 1000:
                cursor.executemany(insert_query, batch_data)
                db.commit()
                print(f"[{datetime.now()}] Progress: {books_processed}/{len(valid_books)} books | Inserted {len(batch_data)} recommendations")
                batch_data = []
        
        # Insert remaining records
        if batch_data:
            cursor.executemany(insert_query, batch_data)
            db.commit()
            print(f"[{datetime.now()}] Inserted final {len(batch_data)} recommendations")
        
        # 9. Update metadata
        print(f"[{datetime.now()}] Updating metadata...")
        cursor.execute("""
        INSERT INTO recommendation_metadata (last_updated, total_books, created_at, updated_at) 
        VALUES (NOW(), %s, NOW(), NOW())
        ON DUPLICATE KEY UPDATE 
            last_updated = NOW(), 
            total_books = %s,
            updated_at = NOW()
        """, (len(valid_books), len(valid_books)))
        db.commit()
        
        # 10. Get final statistics
        cursor.execute("SELECT COUNT(*) FROM book_recommendations")
        total_recommendations = cursor.fetchone()[0]
        
        print("\n" + "="*60)
        print(f"✅ SUCCESS! Recommendation computation completed!")
        print("="*60)
        print(f"📊 Statistics:")
        print(f"   - Books processed: {len(valid_books)}")
        print(f"   - Total recommendations: {total_recommendations}")
        print(f"   - Avg recommendations per book: {total_recommendations // len(valid_books)}")
        print(f"   - Completed at: {datetime.now()}")
        print("="*60)
        
    except mysql.connector.Error as db_err:
        print(f"\n❌ Database Error: {db_err}")
        print("Please check your database credentials and connection.")
        sys.exit(1)
        
    except pd.errors.EmptyDataError:
        print(f"\n❌ Error: No data could be loaded from the database")
        sys.exit(1)
        
    except Exception as e:
        print(f"\n❌ Unexpected Error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
        
    finally:
        if db and db.is_connected():
            cursor.close()
            db.close()
            print(f"[{datetime.now()}] Database connection closed.")

if __name__ == "__main__":
    print("\n" + "="*60)
    print("🤖 AI Recommendation System - Batch Processor")
    print("="*60 + "\n")
    
    compute_all_recommendations()
    
    print("\n✨ Process completed. You can now use AI recommendations in your Laravel app!")