"""
Seed realistic demo data: locations, collection staff (assigned to
locations), customers, loans of every payment type and a payment history
that produces on-time, due-today, overdue and completed loans.

    python manage.py seed_demo_data            # add data (skips if loans exist)
    python manage.py seed_demo_data --force    # add even if loans already exist

Staff login passwords are printed at the end.
"""
import random
from datetime import timedelta, time
from decimal import Decimal

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

from NexusApp.models import (
    AttendanceMaster, Customer, Loan, LoanLead, LoanPayment, Place, Staff,
)
from NexusApp.utils.crypto import encrypt_password
from NexusApp.utils.loan_schedule import nth_due_date as _nth_due_date, skip_sunday

PLACES = ['Nagercoil', 'Marthandam', 'Thuckalay', 'Kuzhithurai', 'Colachel']

STAFF = [
    # name, phone, gender, email, places
    ('Suresh Kumar', '9876543210', 'male', 'suresh.kumar@nexus.in', ['Nagercoil', 'Colachel']),
    ('Priya Lakshmi', '9876543211', 'female', 'priya.lakshmi@nexus.in', ['Marthandam']),
    ('Arul Raj', '9876543212', 'male', 'arul.raj@nexus.in', ['Thuckalay', 'Kuzhithurai']),
]
STAFF_PASSWORD = 'Staff@123'

FIRST = ['Murugan', 'Lakshmi', 'Selvam', 'Kavitha', 'Ravi', 'Anitha', 'Ganesh', 'Meena',
         'Rajesh', 'Saranya', 'Vijay', 'Deepa', 'Karthik', 'Revathi', 'Senthil', 'Malar',
         'Bala', 'Jaya', 'Prakash', 'Uma', 'Mani', 'Geetha', 'Siva', 'Rani']
LAST = ['S', 'R', 'K', 'M', 'P', 'T', 'V', 'A']
STREETS = ['Main Road', 'Church Street', 'Market Road', 'Temple Street', 'North Street', 'Bazaar Road']


class Command(BaseCommand):
    help = 'Seed realistic demo data for testing every flow'

    def add_arguments(self, parser):
        parser.add_argument('--force', action='store_true')

    @transaction.atomic
    def handle(self, *args, **opts):
        if Loan.objects.exists() and not opts['force']:
            self.stdout.write(self.style.WARNING('Loans already exist - use --force to add more.'))
            return

        rng = random.Random(42)
        today = timezone.localdate()

        places = {name: Place.objects.get_or_create(name=name)[0] for name in PLACES}

        if not AttendanceMaster.objects.filter(is_active=True).exists():
            AttendanceMaster.objects.create(
                start_time=time(9, 30), end_time=time(18, 30), late_grace_minutes=15,
                allowed_break_minutes=60,
                working_days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                permission_hours_per_month=4, max_permissions_per_month=2,
                salary_cycle_start_day=1, salary_cycle_end_day=31, salary_payment_day=5,
                is_active=True,
            )

        staff_objs = []
        last = Staff.objects.order_by('id').last()
        next_num = 1
        if last and last.employee_id.replace('EMP', '').isdigit():
            next_num = int(last.employee_id.replace('EMP', '')) + 1
        for name, phone, gender, email, staff_places in STAFF:
            staff = Staff.objects.filter(email__iexact=email).first()
            if staff is None:
                staff = Staff.objects.create(
                    name=name, phone=phone, gender=gender,
                    date_of_birth=today.replace(year=today.year - 30 - len(staff_objs)),
                    address=f'12, {STREETS[len(staff_objs)]}, {staff_places[0]}',
                    employee_id=f'EMP{next_num:03d}', joining_date=today - timedelta(days=400),
                    salary=Decimal('18000.00'), email=email,
                    password=encrypt_password(STAFF_PASSWORD), status='Active',
                )
                next_num += 1
            staff.places.set([places[p] for p in staff_places])
            staff_objs.append(staff)

        staff_for_place = {}
        for staff, (_, _, _, _, sp) in zip(staff_objs, STAFF):
            for p in sp:
                staff_for_place[p] = staff

        plans = [
            # payment_type, amount, dues, due_amount
            ('daily', Decimal('10000'), 100, Decimal('120')),
            ('daily', Decimal('5000'), 50, Decimal('120')),
            ('weekly', Decimal('20000'), 25, Decimal('960')),
            ('weekly', Decimal('15000'), 20, Decimal('900')),
            ('monthly', Decimal('50000'), 12, Decimal('4800')),
            ('monthly', Decimal('30000'), 10, Decimal('3450')),
        ]

        aadhaar_base = 432100000000 + Customer.objects.count() * 7
        loans_created = payments_created = 0
        for i in range(36):
            place_name = PLACES[i % len(PLACES)]
            first, last_initial = FIRST[i % len(FIRST)], LAST[i % len(LAST)]
            customer = Customer.objects.create(
                customer_name=f'{first} {last_initial}',
                phone_number=f'9{rng.randint(100000000, 999999999)}',
                address=f'{rng.randint(1, 200)}, {rng.choice(STREETS)}, {place_name}',
                aadhaar_number=str(aadhaar_base + i * 7),
                referral_name=f'{rng.choice(FIRST)} {rng.choice(LAST)}',
                referral_phone=f'8{rng.randint(100000000, 999999999)}',
            )
            ptype, amount, dues, due_amount = plans[i % len(plans)]
            age_days = {'daily': rng.randint(10, 90), 'weekly': rng.randint(30, 150),
                        'monthly': rng.randint(60, 300)}[ptype]
            loan_date = today - timedelta(days=age_days)
            first_due = skip_sunday(loan_date + timedelta(days={'daily': 1, 'weekly': 7, 'monthly': 30}[ptype]))
            staff = staff_for_place.get(place_name)
            loan = Loan.objects.create(
                customer=customer, place=places[place_name], staff=staff,
                loan_date=loan_date, loan_amount=amount, payment_type=ptype,
                first_due_date=first_due, number_of_dues=dues, due_amount=due_amount,
                notes=f'{ptype.title()} plan - seeded demo loan',
            )
            loans_created += 1

            # how well this customer pays: 0 = completed early, 1 = on time,
            # 2 = a little behind (overdue), 3 = far behind
            behaviour = i % 4 if i % 9 else 0
            elapsed = 0
            while elapsed < dues and _nth_due_date(first_due, ptype, elapsed) <= today:
                elapsed += 1
            if behaviour == 0:
                to_pay = dues
            elif behaviour == 1:
                to_pay = elapsed
            elif behaviour == 2:
                to_pay = max(elapsed - 2, 0)
            else:
                to_pay = max(elapsed // 2, 0)
            to_pay = min(to_pay, dues)

            paid_total = Decimal('0')
            for n in range(to_pay):
                pay_date = min(_nth_due_date(first_due, ptype, n), today)
                if behaviour == 0:
                    pay_date = min(loan_date + timedelta(days=n % 30 + 1), today)
                LoanPayment.objects.create(
                    loan=loan, payment_date=pay_date, amount=due_amount,
                    collected_by=staff, payment_method=rng.choice(['cash', 'cash', 'upi']),
                    payment_status='completed',
                )
                paid_total += due_amount
                payments_created += 1
            if paid_total >= loan.total_payable:
                loan.status = 'completed'
                loan.closed_date = loan.payments.order_by('-payment_date').first().payment_date
                loan.save(update_fields=['status', 'closed_date', 'updated_at'])

        for i in range(6):
            LoanLead.objects.create(
                lead_date=today - timedelta(days=i), followup_date=today + timedelta(days=i + 1),
                name=f'{FIRST[(i + 5) % len(FIRST)]} {LAST[i % len(LAST)]}',
                place=PLACES[i % len(PLACES)], phone=f'7{rng.randint(100000000, 999999999)}',
                loan_type=['personal', 'business', 'vehicle'][i % 3],
                loan_amount=Decimal(str(10000 * (i + 1))),
                payment_type=['daily', 'weekly', 'monthly'][i % 3],
                source=['reference', 'direct', 'social_media', 'advertisement'][i % 4],
                source_details='Seeded lead', staff_name=staff_objs[i % 3].name,
                staff_id=staff_objs[i % 3].employee_id, purpose='Business expansion',
                remarks='Call back after 6 PM',
            )

        self.stdout.write(self.style.SUCCESS(
            f'Seeded {len(PLACES)} places, {len(staff_objs)} staff, '
            f'{loans_created} loans, {payments_created} payments, 6 leads.'))
        for name, _, _, email, sp in STAFF:
            self.stdout.write(f'  staff login: {email} / {STAFF_PASSWORD}  ->  {", ".join(sp)}')
