"""
Script to create sample expenses for testing
"""
import os
import django
import sys
from datetime import datetime, timedelta
from decimal import Decimal
import random

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from expenses.models import Expense
from users.models import CustomUser, Branch
from loans.models import Loan

def create_sample_expenses():
    """Create 15 sample expenses with realistic data"""
    
    print("Creating sample expenses...")
    
    # Get branches
    branches = list(Branch.objects.all())
    if not branches:
        print("Error: No branches found. Please create branches first.")
        return
    
    # Get staff users
    staff_users = list(CustomUser.objects.filter(role__in=['admin', 'team_leader', 'loan_officer', 'secretary']))
    if not staff_users:
        print("Error: No staff users found. Please create staff users first.")
        return
    
    # Get some loans
    loans = list(Loan.objects.filter(status='active')[:5])
    
    # Sample expense data
    sample_expenses = [
        {
            'title': 'Office Rent Payment - November',
            'description': 'Monthly office rent for main branch',
            'category': 'operational',
            'amount': Decimal('45000.00'),
            'payment_method': 'bank',
            'paid_to': 'Nairobi Property Management Ltd',
            'reference_number': 'RENT-NOV-2024',
            'status': 'approved',
            'days_ago': 5,
        },
        {
            'title': 'Staff Salaries - November',
            'description': 'Monthly salary payment for all staff members',
            'category': 'staff',
            'amount': Decimal('180000.00'),
            'payment_method': 'bank',
            'paid_to': 'Staff Payroll',
            'reference_number': 'SAL-NOV-2024',
            'status': 'approved',
            'days_ago': 3,
        },
        {
            'title': 'Marketing Campaign - Social Media',
            'description': 'Facebook and Instagram advertising for loan products',
            'category': 'marketing',
            'amount': Decimal('15000.00'),
            'payment_method': 'mpesa',
            'paid_to': 'Digital Marketing Agency',
            'reference_number': 'MKT-SM-001',
            'status': 'approved',
            'days_ago': 7,
        },
        {
            'title': 'Loan Processing Supplies',
            'description': 'Printing paper, forms, and documentation supplies',
            'category': 'loan_related',
            'amount': Decimal('8500.00'),
            'payment_method': 'cash',
            'paid_to': 'Office Supplies Kenya',
            'reference_number': None,
            'status': 'approved',
            'days_ago': 10,
            'with_loan': True,
        },
        {
            'title': 'Electricity Bill - October',
            'description': 'Monthly electricity bill for all branches',
            'category': 'utilities',
            'amount': Decimal('12300.00'),
            'payment_method': 'mpesa',
            'paid_to': 'Kenya Power',
            'reference_number': 'KPLC-OCT-2024',
            'status': 'approved',
            'days_ago': 15,
        },
        {
            'title': 'Office Furniture Purchase',
            'description': 'New desks and chairs for expansion',
            'category': 'office',
            'amount': Decimal('35000.00'),
            'payment_method': 'bank',
            'paid_to': 'Furniture World Ltd',
            'reference_number': 'FW-INV-4521',
            'status': 'approved',
            'days_ago': 20,
        },
        {
            'title': 'Vehicle Fuel - Branch Operations',
            'description': 'Fuel for field officers and branch operations',
            'category': 'transport',
            'amount': Decimal('18000.00'),
            'payment_method': 'cash',
            'paid_to': 'Total Energies',
            'reference_number': None,
            'status': 'approved',
            'days_ago': 2,
        },
        {
            'title': 'Computer Maintenance',
            'description': 'Repair and maintenance of office computers',
            'category': 'maintenance',
            'amount': Decimal('9500.00'),
            'payment_method': 'mpesa',
            'paid_to': 'Tech Solutions Kenya',
            'reference_number': 'TSK-2024-089',
            'status': 'approved',
            'days_ago': 12,
        },
        {
            'title': 'Internet and Phone Bills',
            'description': 'Monthly internet and phone services',
            'category': 'utilities',
            'amount': Decimal('7800.00'),
            'payment_method': 'mpesa',
            'paid_to': 'Safaricom Business',
            'reference_number': 'SAF-NOV-2024',
            'status': 'pending',
            'days_ago': 1,
        },
        {
            'title': 'Client Acquisition Campaign',
            'description': 'Promotional materials and field marketing',
            'category': 'marketing',
            'amount': Decimal('22000.00'),
            'payment_method': 'bank',
            'paid_to': 'Marketing Solutions Ltd',
            'reference_number': 'MSL-2024-156',
            'status': 'pending',
            'days_ago': 0,
        },
        {
            'title': 'Loan Recovery Transport',
            'description': 'Transport costs for loan recovery visits',
            'category': 'loan_related',
            'amount': Decimal('5500.00'),
            'payment_method': 'cash',
            'paid_to': 'Various Transport',
            'reference_number': None,
            'status': 'pending',
            'days_ago': 1,
            'with_loan': True,
        },
        {
            'title': 'Office Cleaning Services',
            'description': 'Monthly cleaning and sanitation services',
            'category': 'operational',
            'amount': Decimal('6000.00'),
            'payment_method': 'mpesa',
            'paid_to': 'Clean Pro Services',
            'reference_number': 'CPS-NOV-2024',
            'status': 'approved',
            'days_ago': 8,
        },
        {
            'title': 'Staff Training Workshop',
            'description': 'Customer service and loan processing training',
            'category': 'staff',
            'amount': Decimal('25000.00'),
            'payment_method': 'bank',
            'paid_to': 'Professional Training Institute',
            'reference_number': 'PTI-2024-789',
            'status': 'approved',
            'days_ago': 14,
        },
        {
            'title': 'Security Services - November',
            'description': 'Monthly security guard services',
            'category': 'operational',
            'amount': Decimal('28000.00'),
            'payment_method': 'bank',
            'paid_to': 'Secure Guard Ltd',
            'reference_number': 'SGL-NOV-2024',
            'status': 'pending',
            'days_ago': 0,
        },
        {
            'title': 'Stationery and Office Supplies',
            'description': 'General office supplies and stationery',
            'category': 'office',
            'amount': Decimal('4200.00'),
            'payment_method': 'cash',
            'paid_to': 'Stationery Hub',
            'reference_number': None,
            'status': 'approved',
            'days_ago': 6,
        },
    ]
    
    created_count = 0
    
    for expense_data in sample_expenses:
        try:
            # Calculate expense date
            expense_date = datetime.now().date() - timedelta(days=expense_data['days_ago'])
            
            # Select random branch and staff
            branch = random.choice(branches)
            staff = random.choice(staff_users)
            
            # Select loan if needed
            loan = None
            if expense_data.get('with_loan') and loans:
                loan = random.choice(loans)
            
            # Create expense
            expense = Expense.objects.create(
                title=expense_data['title'],
                description=expense_data['description'],
                category=expense_data['category'],
                amount=expense_data['amount'],
                payment_method=expense_data['payment_method'],
                paid_to=expense_data['paid_to'],
                reference_number=expense_data['reference_number'],
                branch=branch,
                staff=staff,
                loan=loan,
                status=expense_data['status'],
                expense_date=expense_date,
            )
            
            # If approved, set approval details
            if expense_data['status'] == 'approved':
                approver = random.choice([u for u in staff_users if u.role in ['admin', 'team_leader']])
                expense.approved_by = approver
                expense.approved_at = datetime.now() - timedelta(days=expense_data['days_ago'] - 1)
                expense.save()
            
            created_count += 1
            print(f"✓ Created: {expense.title} - KES {expense.amount}")
            
        except Exception as e:
            print(f"✗ Error creating expense '{expense_data['title']}': {str(e)}")
    
    print(f"\n✓ Successfully created {created_count} sample expenses!")
    print(f"  - Approved: {Expense.objects.filter(status='approved').count()}")
    print(f"  - Pending: {Expense.objects.filter(status='pending').count()}")
    print(f"  - Total Amount: KES {Expense.objects.filter(status='approved').aggregate(total=models.Sum('amount'))['total'] or 0}")


if __name__ == '__main__':
    from django.db import models
    create_sample_expenses()
