# core/management/commands/send_daily_report.py
"""
Management command to send daily sales report email.
Usage:  python manage.py send_daily_report
        python manage.py send_daily_report --date 2025-03-15

Schedule via cron:
  0 23 * * *  /path/to/venv/bin/python /path/to/manage.py send_daily_report
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import datetime


class Command(BaseCommand):
    help = 'Send daily sales report email to admin(s)'

    def add_arguments(self, parser):
        parser.add_argument(
            '--date',
            type=str,
            default=None,
            help='Date to report on (YYYY-MM-DD). Defaults to today.'
        )

    def handle(self, *args, **options):
        date_str = options.get('date')
        if date_str:
            try:
                report_date = datetime.strptime(date_str, '%Y-%m-%d').date()
            except ValueError:
                self.stderr.write(self.style.ERROR(f'Invalid date format: {date_str}. Use YYYY-MM-DD.'))
                return
        else:
            report_date = timezone.now().date()

        self.stdout.write(f'Sending daily report for {report_date}...')

        from core.email_utils import _do_send_daily_report
        _do_send_daily_report(report_date)

        self.stdout.write(self.style.SUCCESS(f'Daily report sent for {report_date}.'))
