"""
Update expense categories to the new simplified 4-category system
Maps old categories to new ones
"""

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 main():
    print("=" * 80)
    print("UPDATING EXPENSE CATEGORIES")
    print("=" * 80)
    
    # Mapping from old categories to new categories
    category_mapping = {
        'operational': 'other',
        'staff': 'salary',
        'marketing': 'other',
        'loan_related': 'other',
        'utilities': 'other',
        'office': 'office_rent',
        'transport': 'other',
        'maintenance': 'other',
        'other': 'other',
    }
    
    # Get all expenses
    expenses = Expense.objects.all()
    total_count = expenses.count()
    
    print(f"\nTotal expenses to update: {total_count}")
    
    if total_count == 0:
        print("No expenses found. Nothing to update.")
        return
    
    # Count by old category
    print("\nCurrent category distribution:")
    from django.db.models import Count
    category_counts = expenses.values('category').annotate(count=Count('id')).order_by('-count')
    for item in category_counts:
        old_cat = item['category']
        count = item['count']
        new_cat = category_mapping.get(old_cat, 'other')
        print(f"  {old_cat:<20} -> {new_cat:<25} ({count} expenses)")
    
    # Confirm before proceeding
    response = input("\nProceed with category update? (yes/no): ")
    if response.lower() != 'yes':
        print("Update cancelled.")
        return
    
    # Update expenses
    updated_count = 0
    for expense in expenses:
        old_category = expense.category
        new_category = category_mapping.get(old_category, 'other')
        
        if old_category != new_category:
            expense.category = new_category
            expense.save(update_fields=['category'])
            updated_count += 1
    
    print(f"\n✅ Updated {updated_count} expenses")
    
    # Show new distribution
    print("\nNew category distribution:")
    new_category_counts = Expense.objects.values('category').annotate(count=Count('id')).order_by('-count')
    for item in new_category_counts:
        print(f"  {item['category']:<25} {item['count']} expenses")
    
    print("\n" + "=" * 80)
    print("UPDATE COMPLETE")
    print("=" * 80)

if __name__ == '__main__':
    main()
