"""
Demo chit groups (like the design mock-up).

    python manage.py seed_demo_chits            # add demo chits (skips names that exist)
    python manage.py seed_demo_chits --remove   # delete the demo chits again
"""
import random
from datetime import timedelta
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 ChitGroup, ChitMember, ChitPayment, Place
from NexusApp.utils.chit_service import add_months, auction_split, month_start, sync_terms

DEMO = [
    # name, value, members, months, monthly, months_ago (start), due_day
    ('Gold 1 Lakh', 100000, 20, 20, 5000, 6, 5),
    ('Silver 50K', 50000, 25, 25, 2000, 9, 10),
    ('Bronze 25K', 25000, 10, 10, 2500, 10, 1),
    ('Platinum 5 Lakh', 500000, 25, 25, 20000, -1, 15),
]
FIRST = ['Arun', 'Bala', 'Chitra', 'Deepa', 'Ezhil', 'Gokul', 'Hari', 'Indira', 'Jaya', 'Kavin',
         'Lakshmi', 'Mani', 'Nila', 'Prabhu', 'Revathi', 'Selvi', 'Tamil', 'Uma', 'Vasanth', 'Yamuna']
LAST = ['K', 'M', 'R', 'S', 'P', 'V', 'T', 'N']


class Command(BaseCommand):
    help = 'Add (or --remove) demo Monthly Chit Fund groups.'

    def add_arguments(self, parser):
        parser.add_argument('--remove', action='store_true')

    @transaction.atomic
    def handle(self, *args, **opts):
        names = [d[0] for d in DEMO]
        if opts['remove']:
            n, _ = ChitGroup.objects.filter(name__in=names, notes='demo').delete()
            self.stdout.write(f'Removed demo chits ({n} rows).')
            return

        rnd = random.Random(7)
        today = timezone.localdate()
        places = list(Place.objects.order_by('id')[:3])
        for i, (name, value, members, months, monthly, ago, due_day) in enumerate(DEMO):
            if ChitGroup.objects.filter(name=name).exists():
                self.stdout.write(f'skip {name} (exists)')
                continue
            chit = ChitGroup.objects.create(
                name=name, chit_value=Decimal(value), total_members=members, total_months=months,
                monthly_amount=Decimal(monthly), start_month=add_months(month_start(today), -ago),
                due_day=due_day, commission_percent=Decimal('5'), notes='demo',
                place=places[i % len(places)] if places else None)
            sync_terms(chit)
            people = []
            for n in range(1, members + 1):
                people.append(ChitMember.objects.create(
                    chit=chit, ticket_no=n, name=f'{rnd.choice(FIRST)} {rnd.choice(LAST)}',
                    phone=f'9{rnd.randint(100000000, 999999999)}', address='Main Road',
                    joined_date=chit.start_month))
            winners = people[:]
            rnd.shuffle(winners)
            for term in chit.terms.order_by('term_no'):
                if term.due_date > today + timedelta(days=31):
                    break
                past = term.month < month_start(today)
                if term.month <= month_start(today):
                    discount = Decimal(rnd.choice([0, 5000, 10000, 15000])) * Decimal(value) / 100000
                    prize, commission, dividend, due = auction_split(chit, discount)
                    term.bid_discount, term.commission_amount = discount, commission
                    term.dividend_per_member, term.due_amount, term.prize_amount = dividend, due, prize
                    if winners and (past or term.due_date <= today):
                        term.winner = winners.pop()
                        term.claimed = past
                        term.claimed_date = term.due_date if past else None
                    term.save()
                for m in people:
                    if term.month > month_start(today):
                        continue
                    if past and rnd.random() < 0.93 or (not past and rnd.random() < 0.6):
                        amount = term.due_amount if rnd.random() < 0.9 else (term.due_amount / 2).quantize(Decimal('1'))
                        ChitPayment.objects.create(term=term, member=m, amount=amount,
                                                   paid_date=min(term.due_date, today), method=rnd.choice(['cash', 'upi']))
            self.stdout.write(f'added {name}')
        self.stdout.write(self.style.SUCCESS('Demo chits ready.'))
