"""
Monthly Chit Fund rules (shared by the admin and staff screens).

Example: Rs 1,00,000 chit, 20 members, Rs 5,000 a month for 20 months.
Every month the pool is collected and one member takes the prize:
  * auction: winner takes chit value - bid discount; the discount minus the
    organiser's commission is shared by all members as a dividend, so that
    month's due for each member is lower
  * lottery / fixed order: winner takes the full chit value, no dividend
Each member can win only once. The admin can override every month's
due amount and prize amount.
"""
import calendar
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal

from django.db import transaction
from django.db.models import Sum

from NexusApp.models import ChitGroup, ChitMember, ChitPayment, ChitTerm

ZERO = Decimal('0')
TWO = Decimal('0.01')


def month_start(d):
    return d.replace(day=1)


def add_months(d, n):
    m = d.month - 1 + n
    return date(d.year + m // 12, m % 12 + 1, 1)


def term_due_date(month, due_day):
    d = month.replace(day=min(max(due_day, 1), calendar.monthrange(month.year, month.month)[1]))
    return d + timedelta(days=1) if d.weekday() == 6 else d          # no dues on Sundays


def auction_split(chit, discount):
    """(prize, commission, dividend_per_member, due_per_member) for a bid discount."""
    discount = max(Decimal(discount or 0), ZERO)
    commission = (chit.chit_value * chit.commission_percent / 100).quantize(TWO, ROUND_HALF_UP)
    if discount <= 0:
        return chit.chit_value, ZERO, ZERO, chit.monthly_amount
    commission = min(commission, discount)
    members = max(chit.total_members, 1)
    dividend = ((discount - commission) / members).quantize(TWO, ROUND_HALF_UP)
    return chit.chit_value - discount, commission, dividend, max(chit.monthly_amount - dividend, ZERO)


@transaction.atomic
def sync_terms(chit):
    """
    Make sure the chit has exactly total_months terms with the right months.
    Months / due dates follow start_month + due_day. Amounts the admin already
    set are kept; new terms get the chit's default amounts. Extra terms are
    removed only if nothing was paid or won in them.
    """
    start = month_start(chit.start_month)
    existing = {t.term_no: t for t in chit.terms.all()}
    for n in range(1, chit.total_months + 1):
        month = add_months(start, n - 1)
        t = existing.get(n)
        if t is None:
            ChitTerm.objects.create(
                chit=chit, term_no=n, month=month, due_date=term_due_date(month, chit.due_day),
                due_amount=chit.monthly_amount, prize_amount=chit.chit_value)
        elif t.month != month or t.due_date != term_due_date(month, chit.due_day):
            t.month, t.due_date = month, term_due_date(month, chit.due_day)
            t.save(update_fields=['month', 'due_date'])
    blocked = []
    for n, t in existing.items():
        if n > chit.total_months:
            if t.payments.exists() or t.winner_id:
                blocked.append(n)
            else:
                t.delete()
    return blocked


def chit_state(chit, today):
    """'upcoming' | 'active' | 'completed' | 'closed' and the current month number."""
    if chit.status == 'closed':
        return 'closed', None
    start = month_start(chit.start_month)
    now = month_start(today)
    if now < start:
        return 'upcoming', 0
    n = (now.year - start.year) * 12 + now.month - start.month + 1
    if n > chit.total_months:
        return 'completed', chit.total_months
    return 'active', n


def member_status(paid, due, due_date, today):
    if due > 0 and paid >= due:
        return 'Paid'
    if paid > 0:
        return 'Partly paid'
    return 'Overdue' if due_date < today else 'Not paid'


def paid_map(term_ids):
    """(term_id, member_id) -> amount paid."""
    rows = (ChitPayment.objects.filter(term_id__in=term_ids)
            .values('term_id', 'member_id').annotate(s=Sum('amount')))
    return {(r['term_id'], r['member_id']): r['s'] for r in rows}


def term_summary(term, members, paid_lookup, today):
    member_count = len(members)
    due_total = term.due_amount * member_count
    collected = sum((paid_lookup.get((term.id, m.id), ZERO) for m in members), ZERO)
    paid_members = sum(1 for m in members if paid_lookup.get((term.id, m.id), ZERO) >= term.due_amount > 0)
    return {
        'term_id': term.id,
        'term_no': term.term_no,
        'month': term.month.strftime('%b %Y'),
        'month_iso': term.month.isoformat(),
        'due_date': term.due_date.strftime('%d %b %Y'),
        'due_date_iso': term.due_date.isoformat(),
        'due_amount': float(term.due_amount),
        'prize_amount': float(term.prize_amount),
        'bid_discount': float(term.bid_discount),
        'commission_amount': float(term.commission_amount),
        'dividend_per_member': float(term.dividend_per_member),
        'due_total': float(due_total),
        'collected': float(collected),
        'pending': float(max(due_total - collected, ZERO)),
        'paid_members': paid_members,
        'unpaid_members': member_count - paid_members,
        'winner_id': term.winner_id,
        'winner': f'#{term.winner.ticket_no} {term.winner.name}' if term.winner else '',
        'claimed': term.claimed,
        'claimed_date': term.claimed_date.isoformat() if term.claimed_date else '',
        'claimed_label': term.claimed_date.strftime('%d %b %Y') if term.claimed_date else '',
        'notes': term.notes,
        'is_past': term.due_date < today,
        'is_current': month_start(today) == term.month,
    }


def chit_month_numbers(chit, month, today):
    """Cards / list numbers for one chit in a given month (first day)."""
    term = chit.terms.filter(month=month).first()
    members = list(chit.members.all())
    if term is None:
        return {'term': None, 'due': ZERO, 'collected': ZERO, 'pending': ZERO}
    s = term_summary(term, members, paid_map([term.id]), today)
    return {'term': term, 'summary': s, 'due': Decimal(str(s['due_total'])),
            'collected': Decimal(str(s['collected'])), 'pending': Decimal(str(s['pending']))}


def money(v):
    return float(v or 0)


def chit_queryset_for(request):
    """Admin sees every chit; staff only chits of their assigned places."""
    qs = ChitGroup.objects.select_related('place')
    if request.path.startswith('/staff/'):
        from NexusApp.utils.staff_scope import staff_place_ids
        qs = qs.filter(place_id__in=staff_place_ids(getattr(request, 'staff', None)))
    return qs


__all__ = [
    'ChitGroup', 'ChitMember', 'ChitTerm', 'ChitPayment', 'auction_split', 'sync_terms',
    'chit_state', 'member_status', 'paid_map', 'term_summary', 'chit_month_numbers',
    'month_start', 'add_months', 'money', 'chit_queryset_for',
]
