"""
Due-date rules shared by every screen (loan reports, overdue, dashboards).

Sundays are holidays: no due ever falls on a Sunday.
  * daily   - dues run Monday..Saturday, Sundays are skipped
  * weekly  - every 7 days from the first due; a Sunday due moves to Monday
  * monthly - same day each month; a Sunday due moves to Monday
"""
import calendar
from datetime import date, timedelta
from decimal import Decimal

ZERO = Decimal('0')
SUNDAY = 6


def is_sunday(d):
    return d.weekday() == SUNDAY


def skip_sunday(d):
    return d + timedelta(days=1) if is_sunday(d) else d


def add_months(d, months):
    """Add whole months to a date; 31 Jan + 1 month -> 28/29 Feb."""
    m = d.month - 1 + months
    year, month = d.year + m // 12, m % 12 + 1
    return date(year, month, min(d.day, calendar.monthrange(year, month)[1]))


def add_working_days(d, n):
    """Move n working days (Mon-Sat) forward from working day d."""
    weeks, rem = divmod(n, 6)
    d += timedelta(weeks=weeks)
    while rem:
        d += timedelta(days=1)
        if not is_sunday(d):
            rem -= 1
    return d


def nth_due_date(first_due, payment_type, index):
    """Due date of the (index+1)-th due. index 0 = first due (never a Sunday)."""
    if payment_type == 'daily':
        return add_working_days(skip_sunday(first_due), index)
    if payment_type == 'weekly':
        return skip_sunday(first_due + timedelta(weeks=index))
    return skip_sunday(add_months(first_due, index))          # monthly


def working_days_between(start, end):
    """Number of non-Sunday days in [start, end] (0 when end < start)."""
    if end < start:
        return 0
    total = (end - start).days + 1
    weeks, rem = divmod(total, 7)
    count = weeks * 6
    d = start + timedelta(weeks=weeks)
    for _ in range(rem):
        if not is_sunday(d):
            count += 1
        d += timedelta(days=1)
    return count


def dues_elapsed(loan, today):
    """How many dues have fallen due on or before `today`."""
    n = 0
    while n < loan.number_of_dues and \
            nth_due_date(loan.first_due_date, loan.payment_type, n) <= today:
        n += 1
    return n


def last_due_date(loan):
    return nth_due_date(loan.first_due_date, loan.payment_type, max(loan.number_of_dues - 1, 0))


def loan_position(loan, paid, today):
    """
    Everything the reports need about where a loan stands today.

      paid_dues     dues fully covered by the money paid so far
      next_due      first due that is not fully covered (None when completed)
      balance       total payable - paid
      pending_days  working days (no Sundays) from the first unpaid due up to
                    today, i.e. days the customer has not paid
      overdue       amount that should have been paid by today but was not
    """
    due = loan.due_amount or ZERO
    paid = paid or ZERO
    balance = max(loan.total_payable - paid, ZERO)
    completed = loan.status == 'completed' or balance <= 0

    paid_dues = min(int(paid // due), loan.number_of_dues) if due > 0 else 0
    if completed:
        return {
            'completed': True, 'status': 'Completed', 'paid_dues': loan.number_of_dues
            if balance <= 0 else paid_dues, 'next_due': None, 'balance': balance,
            'pending_days': 0, 'overdue': ZERO, 'elapsed': dues_elapsed(loan, today),
        }

    next_due = nth_due_date(loan.first_due_date, loan.payment_type, paid_dues)
    elapsed = dues_elapsed(loan, today)
    # overdue = dues dated before today that are still unpaid (today's due is not late yet)
    should_have_paid = min(due * dues_elapsed(loan, today - timedelta(days=1)), loan.total_payable)
    overdue = max(should_have_paid - paid, ZERO)

    if next_due < today:
        status = 'Overdue'
    elif next_due == today:
        status = 'Due Today'
    else:
        status = 'In-Time'

    # today's due counts as not paid until it is paid
    pending_days = working_days_between(next_due, today) if next_due <= today else 0

    return {
        'completed': False, 'status': status, 'paid_dues': paid_dues,
        'next_due': next_due, 'balance': balance, 'pending_days': pending_days,
        'overdue': overdue, 'elapsed': elapsed,
    }


def period_report(loan, payments, today, period):
    """
    Week-by-week (Mon-Sat) or month-by-month view of one loan:
    what fell due in the period, what was paid in it, and the running balance.
    """
    due = loan.due_amount or ZERO

    def period_start(d):
        if period == 'weekly':
            return d - timedelta(days=d.weekday())
        return d.replace(day=1)

    def next_start(s):
        return s + timedelta(weeks=1) if period == 'weekly' else add_months(s, 1)

    due_dates = [nth_due_date(loan.first_due_date, loan.payment_type, i)
                 for i in range(loan.number_of_dues)]
    first = min([loan.first_due_date] + [p.payment_date for p in payments])
    start = period_start(first)
    # up to today (or the last due if the loan ends earlier), plus any later payment
    stop = max([min(today, last_due_date(loan))] + [p.payment_date for p in payments])

    rows, expected_total, paid_total = [], ZERO, ZERO
    while start <= stop:
        nxt = next_start(start)
        period_end = nxt - timedelta(days=1)
        dues_in = sum(1 for d in due_dates if start <= d <= period_end and d <= today)
        expected = min(due * dues_in, max(loan.total_payable - expected_total, ZERO))
        paid = sum((p.amount for p in payments if start <= p.payment_date <= period_end), ZERO)
        behind_before = expected_total > paid_total
        expected_total += expected
        paid_total += paid
        shortfall = max(expected_total - paid_total, ZERO)
        if not dues_in and not paid:          # nothing due and nothing paid: skip the period
            start = nxt
            continue
        if expected > 0:
            status = 'Paid' if paid >= expected else ('Partly paid' if paid > 0 else 'Not paid')
        else:
            status = 'Arrears paid' if behind_before else 'Advance'
        if period == 'weekly':
            label = f"{start.strftime('%d %b')} - {(start + timedelta(days=5)).strftime('%d %b %Y')}"
        else:
            label = start.strftime('%B %Y')
        rows.append({
            'period': label,
            'dues': dues_in,
            'expected': float(expected),
            'paid': float(paid),
            'pending': float(max(expected - paid, ZERO)),
            'extra': float(max(paid - expected, ZERO)),
            'shortfall': float(shortfall),
            'balance': float(max(loan.total_payable - paid_total, ZERO)),
            'status': status,
        })
        start = nxt
    rows.reverse()                       # newest period first
    return rows
