"""
Direct MySQL script to recategorize existing expenses in production
Uses direct database connection - no Django required
"""

import pymysql
from collections import defaultdict

# Production database credentials
DB_CONFIG = {
    'host': 'localhost',
    'database': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB'
}

def categorize_expense(title):
    """
    Automatically categorize expenses based on title keywords
    Returns one of: 'salary', 'office_rent', 'bank_mpesa_charges', 'other'
    """
    title_lower = title.lower()
    
    # 1. SALARY - salary, allowance, advance, wage
    salary_keywords = [
        'salary', 'allowance', 'allowances', 'advance', 'wage', 
        'wages', 'pay', 'frashia', 'to elijah'
    ]
    if any(keyword in title_lower for keyword in salary_keywords):
        return 'salary'
    
    # 2. OFFICE RENT - rent, lease
    rent_keywords = ['rent', 'lease']
    if any(keyword in title_lower for keyword in rent_keywords):
        return 'office_rent'
    
    # 3. BANK AND MPESA CHARGES - bank, mpesa, safaricom, transfer, charges
    bank_mpesa_keywords = [
        'bank', 'mpesa', 'm-pesa', 'safaricom', 'transfer', 'charges',
        'charge', 'statement', 'transaction fee', 'withdrawal'
    ]
    if any(keyword in title_lower for keyword in bank_mpesa_keywords):
        return 'bank_mpesa_charges'
    
    # 4. OTHER EXPENSES - everything else
    return 'other'

def main():
    print("=" * 100)
    print("RECATEGORIZE EXISTING EXPENSES - PRODUCTION")
    print("=" * 100)
    print(f"Database: {DB_CONFIG['database']}")
    print(f"Host: {DB_CONFIG['host']}")
    
    try:
        # Connect to database
        print("\nConnecting to database...")
        conn = pymysql.connect(
            host=DB_CONFIG['host'],
            database=DB_CONFIG['database'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password']
        )
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        
        # Get all expenses
        cursor.execute("SELECT id, title, category FROM expenses ORDER BY id")
        expenses = cursor.fetchall()
        total_count = len(expenses)
        
        print(f"✓ Found {total_count} expenses")
        
        if total_count == 0:
            print("No expenses to recategorize.")
            conn.close()
            return
        
        # Analyze current categories
        current_distribution = defaultdict(int)
        for exp in expenses:
            current_distribution[exp['category']] += 1
        
        print(f"\nCURRENT CATEGORY DISTRIBUTION:")
        for cat, count in sorted(current_distribution.items(), key=lambda x: -x[1]):
            print(f"  {cat:<20} {count:>5} expenses")
        
        # Preview recategorization (first 20)
        print(f"\n{'=' * 100}")
        print("PREVIEW: First 20 expenses will be recategorized as:")
        print(f"{'ID':<6} {'Current Cat':<20} {'Title':<40} {'New Cat':<25}")
        print("-" * 100)
        
        for exp in expenses[:20]:
            new_cat = categorize_expense(exp['title'])
            print(f"{exp['id']:<6} {exp['category']:<20} {exp['title'][:38]:<40} {new_cat:<25}")
        
        # Count changes and final distribution
        total_changed = 0
        final_distribution = defaultdict(int)
        
        for exp in expenses:
            new_cat = categorize_expense(exp['title'])
            final_distribution[new_cat] += 1
            if new_cat != exp['category']:
                total_changed += 1
        
        print(f"\n{'=' * 100}")
        print("RECATEGORIZATION SUMMARY:")
        print(f"Total expenses: {total_count}")
        print(f"Will be changed: {total_changed}")
        print(f"Will stay same: {total_count - total_changed}")
        
        print(f"\nNEW CATEGORY DISTRIBUTION:")
        print(f"{'Category':<30} {'Count':>10} {'Percentage':>12}")
        print("-" * 55)
        for cat in ['salary', 'office_rent', 'bank_mpesa_charges', 'other']:
            count = final_distribution[cat]
            pct = (count / total_count * 100) if total_count > 0 else 0
            display_name = cat.replace('_', ' ').title()
            print(f"{display_name:<30} {count:>10} {pct:>11.1f}%")
        
        # Proceed with update
        print(f"\n{'=' * 100}")
        print("Proceeding with recategorization...")
        
        updated = 0
        unchanged = 0
        errors = []
        
        print(f"\nRecategorizing {total_count} expenses...")
        
        for exp in expenses:
            try:
                new_category = categorize_expense(exp['title'])
                
                if exp['category'] != new_category:
                    # Update the category
                    update_query = "UPDATE expenses SET category = %s WHERE id = %s"
                    cursor.execute(update_query, (new_category, exp['id']))
                    updated += 1
                else:
                    unchanged += 1
                
                if (updated + unchanged) % 20 == 0:
                    print(f"  Processed {updated + unchanged}/{total_count}...")
                    
            except Exception as e:
                errors.append(f"ID {exp['id']}: {str(e)}")
        
        # Commit all changes
        conn.commit()
        
        # Final summary
        print(f"\n{'=' * 100}")
        print("RECATEGORIZATION COMPLETE")
        print(f"{'=' * 100}")
        print(f"✅ Updated: {updated}")
        print(f"⏭️  Unchanged: {unchanged}")
        
        if errors:
            print(f"❌ Errors: {len(errors)}")
            print("\nFirst 5 errors:")
            for error in errors[:5]:
                print(f"  - {error}")
        
        # Verify final distribution
        cursor.execute("""
            SELECT category, COUNT(*) as count 
            FROM expenses 
            GROUP BY category 
            ORDER BY count DESC
        """)
        final_db_distribution = cursor.fetchall()
        
        print(f"\nFINAL DATABASE CATEGORY DISTRIBUTION:")
        for row in final_db_distribution:
            cat_display = row['category'].replace('_', ' ').title()
            print(f"  {cat_display:<30} {row['count']:>5} expenses")
        
        print(f"\n{'=' * 100}")
        print("✅ All existing expenses have been recategorized!")
        print(f"{'=' * 100}")
        
        # Close connection
        cursor.close()
        conn.close()
        
    except pymysql.Error as e:
        print(f"\n❌ Database error: {e}")
        return 1
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        return 1
    
    return 0

if __name__ == '__main__':
    exit(main())
