"""
Email out queued AR/AP payment reminders for all active branches.

Intended to run on a daily production schedule, e.g.:

  Linux cron (08:00 daily):
    0 8 * * * cd /path/to/backend && /path/to/venv/bin/python manage.py dispatch_finance_reminders

  Windows Task Scheduler (daily):
    Program:   D:\\xampp\\htdocs\\megawatt-erp\\backend\\venv\\Scripts\\python.exe
    Arguments: manage.py dispatch_finance_reminders
    Start in:  D:\\xampp\\htdocs\\megawatt-erp\\backend

Pair it with `run_finance_automation` (which builds the reminder queue) — run
that first, then this command to send the emails.
"""
from django.core.management.base import BaseCommand

from finance_and_accounting.finance_extended import (
    dispatch_due_reminders,
    generate_due_reminders,
)
from system_administration.models import CompanyBranch


class Command(BaseCommand):
    help = "Generate and email AR/AP due reminders for all active branches."

    def add_arguments(self, parser):
        parser.add_argument(
            "--no-generate", action="store_true",
            help="Only send already-queued reminders; skip regenerating the queue.",
        )

    def handle(self, *args, **options):
        total_created = 0
        total_sent = 0
        total_failed = 0
        for branch in CompanyBranch.objects.filter(recycle_bin=False, branch_active=True):
            if not options["no_generate"]:
                created = generate_due_reminders(branch).get("reminders_created", 0)
                total_created += created
            result = dispatch_due_reminders(branch)
            total_sent += result.get("sent", 0)
            total_failed += result.get("failed", 0)
            if result.get("sent") or result.get("failed"):
                self.stdout.write(
                    f"Branch {branch.branch_name}: {result.get('sent', 0)} sent, "
                    f"{result.get('failed', 0)} failed"
                )
        self.stdout.write(self.style.SUCCESS(
            f"Done — {total_created} queued, {total_sent} sent, {total_failed} failed."
        ))
