"""
Smart script to import expenses from SQL file and automatically categorize them
into the new 4-category system based on keywords in the title
"""

import os
import sys
import django
import re
from decimal import Decimal

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
from users.models import Branch
from django.contrib.auth import get_user_model

User = get_user_model()

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 parse_sql_insert(line):
    """
    Parse a single INSERT INTO line and extract expense data
    Returns dict with expense fields or None if parsing fails
    """
    # Pattern to match: (id, 'title', 'description', 'category', amount, 'payment_method', ...)
    pattern = r"\((\d+),\s*'([^']*)',\s*'([^']*)',\s*'([^']*)',\s*([0-9.]+),\s*'([^']*)',\s*'([^']*)',\s*'([^']*)',\s*'([^']*)',\s*([^,]+),\s*([^,]+),\s*'([^']*)',\s*'([^']*)',\s*'([^']*)',\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*'([^']*)',\s*([^,]+),\s*([^,]+)\)"
    
    match = re.search(pattern, line)
    if not match:
        return None
    
    try:
        return {
            'id': int(match.group(1)),
            'title': match.group(2),
            'description': match.group(3),
            'old_category': match.group(4),
            'amount': Decimal(match.group(5)),
            'payment_method': match.group(6),
            'paid_to': match.group(7),
            'receipt_path': match.group(8) if match.group(8) else '',
            'status': match.group(9),
            'expense_date': match.group(12),  # YYYY-MM-DD format
        }
    except Exception as e:
        print(f"Error parsing line: {e}")
        return None

def main():
    print("=" * 100)
    print("SMART EXPENSE IMPORT & CATEGORIZATION")
    print("=" * 100)
    
    sql_file_path = r"C:\Users\BEST\Downloads\expenses.sql"
    
    if not os.path.exists(sql_file_path):
        print(f"❌ Error: SQL file not found at {sql_file_path}")
        return
    
    print(f"\nReading expenses from: {sql_file_path}")
    
    # Read SQL file
    with open(sql_file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Find all INSERT INTO statements
    insert_lines = []
    for line in content.split('\n'):
        if line.strip().startswith('(') and ',' in line:
            insert_lines.append(line)
    
    print(f"Found {len(insert_lines)} expense records in SQL file")
    
    # Parse all expenses
    parsed_expenses = []
    for line in insert_lines:
        expense_data = parse_sql_insert(line)
        if expense_data:
            parsed_expenses.append(expense_data)
    
    print(f"Successfully parsed {len(parsed_expenses)} expenses")
    
    if not parsed_expenses:
        print("❌ No expenses could be parsed. Check the SQL file format.")
        return
    
    # Show category distribution preview
    print(f"\nCATEGORY PREVIEW (first 20 expenses):")
    print(f"{'ID':<6} {'Title':<50} {'Old Cat':<15} {'New Cat':<25}")
    print("-" * 100)
    
    category_counts = {'salary': 0, 'office_rent': 0, 'bank_mpesa_charges': 0, 'other': 0}
    
    for i, exp in enumerate(parsed_expenses[:20]):
        new_cat = categorize_expense(exp['title'])
        category_counts[new_cat] += 1
        print(f"{exp['id']:<6} {exp['title'][:48]:<50} {exp['old_category']:<15} {new_cat:<25}")
    
    # Count all categories
    for exp in parsed_expenses[20:]:
        new_cat = categorize_expense(exp['title'])
        category_counts[new_cat] += 1
    
    print(f"\nFULL CATEGORIZATION SUMMARY:")
    print(f"{'Category':<30} {'Count':>10} {'Percentage':>12}")
    print("-" * 55)
    total = len(parsed_expenses)
    for cat, count in sorted(category_counts.items(), key=lambda x: -x[1]):
        pct = (count / total * 100) if total > 0 else 0
        display_name = cat.replace('_', ' ').title()
        print(f"{display_name:<30} {count:>10} {pct:>11.1f}%")
    print(f"{'TOTAL':<30} {total:>10} {100.0:>11.1f}%")
    
    # Auto-proceed (non-interactive)
    print(f"\n{'=' * 100}")
    print("Proceeding with automatic import...")
    
    # Get default branch and user
    try:
        default_branch = Branch.objects.first()
        default_user = User.objects.filter(is_staff=True).first()
        
        if not default_branch:
            print("❌ Error: No branch found in database. Create at least one branch first.")
            return
        
        if not default_user:
            print("❌ Error: No staff user found in database.")
            return
        
        print(f"\nUsing Branch: {default_branch.name}")
        print(f"Using Staff: {default_user.get_full_name() or default_user.username}")
        
    except Exception as e:
        print(f"❌ Error getting default branch/user: {e}")
        return
    
    # Import expenses
    print(f"\nImporting {len(parsed_expenses)} expenses...")
    imported = 0
    skipped = 0
    errors = []
    
    for exp_data in parsed_expenses:
        try:
            # Check if expense with this ID already exists
            if Expense.objects.filter(id=exp_data['id']).exists():
                skipped += 1
                continue
            
            # Categorize
            new_category = categorize_expense(exp_data['title'])
            
            # Create expense
            expense = Expense.objects.create(
                id=exp_data['id'],
                title=exp_data['title'],
                description=exp_data['description'],
                category=new_category,  # NEW CATEGORY!
                amount=exp_data['amount'],
                payment_method=exp_data['payment_method'],
                paid_to=exp_data['paid_to'],
                receipt_path=exp_data['receipt_path'],
                status=exp_data['status'],
                expense_date=exp_data['expense_date'],
                branch=default_branch,
                staff=default_user,
            )
            imported += 1
            
            if imported % 20 == 0:
                print(f"  Imported {imported}/{len(parsed_expenses)}...")
        
        except Exception as e:
            errors.append(f"ID {exp_data['id']}: {str(e)}")
    
    # Final summary
    print(f"\n{'=' * 100}")
    print("IMPORT COMPLETE")
    print(f"{'=' * 100}")
    print(f"✅ Imported: {imported}")
    print(f"⏭️  Skipped (already exist): {skipped}")
    if errors:
        print(f"❌ Errors: {len(errors)}")
        print("\nFirst 5 errors:")
        for error in errors[:5]:
            print(f"  - {error}")
    
    # Show final category distribution
    print(f"\nFINAL DATABASE CATEGORY DISTRIBUTION:")
    from django.db.models import Count
    category_distribution = Expense.objects.values('category').annotate(count=Count('id')).order_by('-count')
    
    for item in category_distribution:
        cat_display = item['category'].replace('_', ' ').title()
        print(f"  {cat_display:<30} {item['count']:>5} expenses")
    
    print(f"\n{'=' * 100}")

if __name__ == '__main__':
    main()
