"""
Demo script to showcase all Expenses Management features
"""
import os
import 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
from django.db.models import Sum, Count, Avg
from datetime import datetime, timedelta

def print_header(title):
    print("\n" + "=" * 70)
    print(f"  {title}")
    print("=" * 70)

def demo_basic_stats():
    print_header("📊 BASIC STATISTICS")
    
    total = Expense.objects.count()
    approved = Expense.objects.filter(status='approved').count()
    pending = Expense.objects.filter(status='pending').count()
    
    total_amount = Expense.objects.filter(status='approved').aggregate(
        total=Sum('amount')
    )['total'] or 0
    
    avg_amount = Expense.objects.filter(status='approved').aggregate(
        avg=Avg('amount')
    )['avg'] or 0
    
    print(f"\n  Total Expenses: {total}")
    print(f"  Approved: {approved}")
    print(f"  Pending: {pending}")
    print(f"  Total Amount: KES {total_amount:,.2f}")
    print(f"  Average Amount: KES {avg_amount:,.2f}")

def demo_category_breakdown():
    print_header("📁 CATEGORY BREAKDOWN")
    
    categories = Expense.objects.values('category').annotate(
        count=Count('id'),
        total=Sum('amount')
    ).order_by('-total')
    
    print(f"\n  {'Category':<20} {'Count':<10} {'Total Amount':<20}")
    print(f"  {'-'*50}")
    
    for cat in categories:
        print(f"  {cat['category'].title():<20} {cat['count']:<10} KES {cat['total']:>15,.2f}")

def demo_branch_breakdown():
    print_header("🏢 BRANCH BREAKDOWN")
    
    branches = Expense.objects.values('branch__name').annotate(
        count=Count('id'),
        total=Sum('amount')
    ).order_by('-total')
    
    print(f"\n  {'Branch':<25} {'Count':<10} {'Total Amount':<20}")
    print(f"  {'-'*55}")
    
    for branch in branches:
        print(f"  {branch['branch__name']:<25} {branch['count']:<10} KES {branch['total']:>15,.2f}")

def demo_payment_methods():
    print_header("💳 PAYMENT METHODS")
    
    methods = Expense.objects.values('payment_method').annotate(
        count=Count('id'),
        total=Sum('amount')
    ).order_by('-total')
    
    print(f"\n  {'Method':<20} {'Count':<10} {'Total Amount':<20}")
    print(f"  {'-'*50}")
    
    for method in methods:
        print(f"  {method['payment_method'].title():<20} {method['count']:<10} KES {method['total']:>15,.2f}")

def demo_recent_expenses():
    print_header("📅 RECENT EXPENSES (Last 5)")
    
    recent = Expense.objects.select_related('branch', 'staff').order_by('-created_at')[:5]
    
    print(f"\n  {'Date':<12} {'Title':<30} {'Amount':<15} {'Status':<10}")
    print(f"  {'-'*67}")
    
    for exp in recent:
        print(f"  {exp.expense_date.strftime('%Y-%m-%d'):<12} {exp.title[:28]:<30} KES {exp.amount:>10,.2f} {exp.status:<10}")

def demo_pending_approvals():
    print_header("⏳ PENDING APPROVALS")
    
    pending = Expense.objects.filter(status='pending').select_related('branch', 'staff')
    
    if pending.exists():
        print(f"\n  {'Title':<35} {'Amount':<15} {'Branch':<20}")
        print(f"  {'-'*70}")
        
        for exp in pending:
            print(f"  {exp.title[:33]:<35} KES {exp.amount:>10,.2f} {exp.branch.name:<20}")
    else:
        print("\n  ✅ No pending approvals!")

def demo_top_expenses():
    print_header("💰 TOP 5 EXPENSES")
    
    top = Expense.objects.filter(status='approved').order_by('-amount')[:5]
    
    print(f"\n  {'Title':<35} {'Amount':<15} {'Category':<15}")
    print(f"  {'-'*65}")
    
    for exp in top:
        print(f"  {exp.title[:33]:<35} KES {exp.amount:>10,.2f} {exp.get_category_display():<15}")

def demo_loan_related():
    print_header("🔗 LOAN-RELATED EXPENSES")
    
    loan_expenses = Expense.objects.filter(loan__isnull=False).select_related('loan', 'loan__borrower')
    
    if loan_expenses.exists():
        print(f"\n  {'Title':<30} {'Amount':<15} {'Loan Borrower':<25}")
        print(f"  {'-'*70}")
        
        for exp in loan_expenses:
            borrower = exp.loan.borrower.get_full_name()
            print(f"  {exp.title[:28]:<30} KES {exp.amount:>10,.2f} {borrower:<25}")
    else:
        print("\n  No loan-related expenses found.")

def demo_monthly_trend():
    print_header("📈 MONTHLY TREND (Last 6 Months)")
    
    today = datetime.now().date()
    
    print(f"\n  {'Month':<15} {'Count':<10} {'Total Amount':<20}")
    print(f"  {'-'*45}")
    
    for i in range(6):
        month_date = today.replace(day=1) - timedelta(days=i*30)
        month_start = month_date.replace(day=1)
        
        if month_date.month == 12:
            month_end = month_date.replace(year=month_date.year + 1, month=1, day=1) - timedelta(days=1)
        else:
            month_end = month_date.replace(month=month_date.month + 1, day=1) - timedelta(days=1)
        
        month_expenses = Expense.objects.filter(
            status='approved',
            expense_date__gte=month_start,
            expense_date__lte=month_end
        )
        
        count = month_expenses.count()
        total = month_expenses.aggregate(total=Sum('amount'))['total'] or 0
        
        print(f"  {month_start.strftime('%b %Y'):<15} {count:<10} KES {total:>15,.2f}")

def demo_staff_expenses():
    print_header("👥 EXPENSES BY STAFF")
    
    staff_expenses = Expense.objects.values('staff__first_name', 'staff__last_name').annotate(
        count=Count('id'),
        total=Sum('amount')
    ).order_by('-count')[:5]
    
    print(f"\n  {'Staff Member':<30} {'Count':<10} {'Total Amount':<20}")
    print(f"  {'-'*60}")
    
    for staff in staff_expenses:
        name = f"{staff['staff__first_name']} {staff['staff__last_name']}"
        print(f"  {name:<30} {staff['count']:<10} KES {staff['total']:>15,.2f}")

def demo_summary():
    print_header("📋 SUMMARY")
    
    today = datetime.now().date()
    current_month_start = today.replace(day=1)
    current_year_start = today.replace(month=1, day=1)
    
    today_total = Expense.objects.filter(
        status='approved',
        expense_date=today
    ).aggregate(total=Sum('amount'))['total'] or 0
    
    month_total = Expense.objects.filter(
        status='approved',
        expense_date__gte=current_month_start
    ).aggregate(total=Sum('amount'))['total'] or 0
    
    year_total = Expense.objects.filter(
        status='approved',
        expense_date__gte=current_year_start
    ).aggregate(total=Sum('amount'))['total'] or 0
    
    print(f"\n  📅 Today's Expenses: KES {today_total:,.2f}")
    print(f"  📅 This Month: KES {month_total:,.2f}")
    print(f"  📅 This Year: KES {year_total:,.2f}")
    
    pending_count = Expense.objects.filter(status='pending').count()
    print(f"\n  ⏳ Pending Approvals: {pending_count}")
    
    # Top category
    top_cat = Expense.objects.filter(status='approved').values('category').annotate(
        total=Sum('amount')
    ).order_by('-total').first()
    
    if top_cat:
        print(f"  🏆 Top Category: {top_cat['category'].title()} (KES {top_cat['total']:,.2f})")

def main():
    print("\n")
    print("╔" + "═" * 68 + "╗")
    print("║" + " " * 15 + "EXPENSES MANAGEMENT SYSTEM DEMO" + " " * 22 + "║")
    print("║" + " " * 20 + "HAVEN GRAZURI Advance" + " " * 25 + "║")
    print("╚" + "═" * 68 + "╝")
    
    demo_basic_stats()
    demo_category_breakdown()
    demo_branch_breakdown()
    demo_payment_methods()
    demo_recent_expenses()
    demo_pending_approvals()
    demo_top_expenses()
    demo_loan_related()
    demo_monthly_trend()
    demo_staff_expenses()
    demo_summary()
    
    print("\n" + "=" * 70)
    print("  ✅ DEMO COMPLETE - All features working perfectly!")
    print("=" * 70)
    print("\n  🚀 Ready to use the Expenses Management System!")
    print("  📖 Check EXPENSES_USER_GUIDE.md for detailed instructions")
    print("\n")

if __name__ == '__main__':
    main()
