"""
Smart script to recategorize EXISTING expenses in production database
Finds expenses by title and automatically assigns new categories
"""

import os
import sys
import django

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from expenses.models import Expense

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")
    print("=" * 100)
    
    # Get ALL expenses from database
    all_expenses = Expense.objects.all()
    total_count = all_expenses.count()
    
    print(f"\nTotal expenses in database: {total_count}")
    
    if total_count == 0:
        print("❌ No expenses found in database.")
        return
    
    # Analyze current categories
    print(f"\nCURRENT CATEGORY DISTRIBUTION:")
    from django.db.models import Count
    current_distribution = all_expenses.values('category').annotate(count=Count('id')).order_by('-count')
    
    for item in current_distribution:
        print(f"  {item['category']:<20} {item['count']:>5} expenses")
    
    # Preview recategorization
    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)
    
    category_changes = {'salary': 0, 'office_rent': 0, 'bank_mpesa_charges': 0, 'other': 0}
    changed_count = 0
    
    # Preview first 20
    for exp in all_expenses[:20]:
        new_cat = categorize_expense(exp.title)
        if new_cat != exp.category:
            changed_count += 1
        category_changes[new_cat] += 1
        print(f"{exp.id:<6} {exp.category:<20} {exp.title[:38]:<40} {new_cat:<25}")
    
    # Count all changes
    total_changed = 0
    for exp in all_expenses:
        new_cat = categorize_expense(exp.title)
        if new_cat != exp.category:
            total_changed += 1
    
    # Count final distribution
    final_distribution = {'salary': 0, 'office_rent': 0, 'bank_mpesa_charges': 0, 'other': 0}
    for exp in all_expenses:
        new_cat = categorize_expense(exp.title)
        final_distribution[new_cat] += 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}%")
    
    # Auto-proceed (non-interactive)
    print(f"\n{'=' * 100}")
    print("Proceeding with automatic recategorization...")
    
    # Update all expenses
    updated = 0
    unchanged = 0
    errors = []
    
    print(f"\nRecategorizing {total_count} expenses...")
    
    for exp in all_expenses:
        try:
            new_category = categorize_expense(exp.title)
            
            if exp.category != new_category:
                exp.category = new_category
                exp.save(update_fields=['category'])
                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)}")
    
    # 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}")
    
    # Show final distribution from database
    print(f"\nFINAL DATABASE CATEGORY DISTRIBUTION:")
    final_db_distribution = Expense.objects.values('category').annotate(count=Count('id')).order_by('-count')
    
    for item in final_db_distribution:
        cat_display = item['category'].replace('_', ' ').title()
        print(f"  {cat_display:<30} {item['count']:>5} expenses")
    
    print(f"\n{'=' * 100}")
    print("✅ All existing expenses have been recategorized!")
    print(f"{'=' * 100}")

if __name__ == '__main__':
    main()
