# core/management/commands/send_daily_report.py
"""
Management command to send daily business summary emails to each company's admin.
Uses analytics.email_reports.send_daily_report(company) which is the correct
per-company version that sends to business_email / company admin — NOT the
platform owner's email.

Usage:
  python manage.py send_daily_report
  python manage.py send_daily_report --date 2025-03-15
  python manage.py send_daily_report --company demo-company   (single company slug)

Schedule via cron (WAT midnight = 23:00 UTC):
  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 business summary email to each company admin'

    def add_arguments(self, parser):
        parser.add_argument(
            '--date',
            type=str,
            default=None,
            help='Date to report on (YYYY-MM-DD). Defaults to yesterday.',
        )
        parser.add_argument(
            '--company',
            type=str,
            default=None,
            help='Slug of a single company to send to (for testing).',
        )

    def handle(self, *args, **options):
        date_str = options.get('date')
        company_slug = options.get('company')

        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:
            # Default: yesterday's data (report is run at end of day)
            report_date = (timezone.now() - timezone.timedelta(days=1)).date()

        from companies.models import Company
        from analytics.email_reports import send_daily_report

        if company_slug:
            companies = Company.objects.filter(slug=company_slug, is_active=True)
        else:
            # All active companies that have email reporting enabled
            companies = Company.objects.filter(
                is_active=True,
                settings__enable_email=True,
            ).select_related('settings')

        total = companies.count()
        sent = 0
        skipped = 0

        self.stdout.write(f'Sending daily report for {report_date} to {total} company/companies...')

        for company in companies:
            try:
                result = send_daily_report(company)
                if result:
                    sent += 1
                    self.stdout.write(f'  ✓ Sent to: {company.name}')
                else:
                    skipped += 1
                    self.stdout.write(self.style.WARNING(f'  ⚠ Skipped (no email or disabled): {company.name}'))
            except Exception as e:
                skipped += 1
                self.stderr.write(self.style.ERROR(f'  ✗ Failed for {company.name}: {e}'))

        self.stdout.write(self.style.SUCCESS(
            f'\nDone. Sent: {sent}, Skipped/Failed: {skipped} — Report date: {report_date}'
        ))
