# analytics/management/commands/generate_insights.py
"""
Django management command: python manage.py generate_insights

Run this daily at midnight WAT via cron (same pattern as process_subscriptions).

Example cron (Linux/cPanel):
  0 0 * * * /path/to/python /path/to/manage.py generate_insights

Example Windows Task Scheduler:
  python manage.py generate_insights
"""
import logging
from django.core.management.base import BaseCommand
from django.utils import timezone

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Generate business insights, stock forecasts, and send daily email reports for all active companies.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--company',
            type=str,
            default=None,
            help='Slug of a specific company (default: all active companies)',
        )
        parser.add_argument(
            '--skip-email',
            action='store_true',
            default=False,
            help='Skip sending email reports',
        )
        parser.add_argument(
            '--skip-forecast',
            action='store_true',
            default=False,
            help='Skip stock forecasting',
        )

    def handle(self, *args, **options):
        from companies.models import Company
        from analytics.services import InsightEngine
        from analytics.forecasting import StockForecaster
        from analytics.email_reports import send_daily_report
        from analytics.models import Insight

        company_slug = options.get('company')
        skip_email = options.get('skip_email', False)
        skip_forecast = options.get('skip_forecast', False)

        if company_slug:
            companies = Company.objects.filter(slug=company_slug, is_active=True)
        else:
            companies = Company.objects.filter(is_active=True)

        if not companies.exists():
            self.stdout.write(self.style.WARNING('No active companies found.'))
            return

        self.stdout.write(f"Processing {companies.count()} company(ies)...")

        # 1. Purge old insights (>30 days)
        Insight.purge_old(days=30)
        self.stdout.write("[OK] Old insights purged (>30 days)")

        total_insights = 0
        total_forecasts = 0
        total_emails = 0

        for company in companies:
            self.stdout.write(f"\n[COMPANY] {company.name} ({company.slug})")

            try:
                # 2. Stock forecasting (runs first — insights depend on it)
                if not skip_forecast:
                    forecaster = StockForecaster(company)
                    count = forecaster.update_all()
                    total_forecasts += count
                    self.stdout.write(f"  --> Forecast: {count} products updated")
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"  [ERROR] Forecast error: {e}"))
                logger.error(f"[generate_insights] Forecast error for {company.slug}: {e}")

            try:
                # 3. Generate insights
                engine = InsightEngine(company)
                engine.generate_all()
                today_count = Insight.objects.filter(
                    company=company, created_at__date=timezone.now().date()
                ).count()
                total_insights += today_count
                self.stdout.write(f"  --> Insights: {today_count} generated/updated today")
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"  [ERROR] Insight error: {e}"))
                logger.error(f"[generate_insights] Insight error for {company.slug}: {e}")

            try:
                # 4. Send daily email report
                if not skip_email:
                    sent = send_daily_report(company)
                    if sent:
                        total_emails += 1
                        self.stdout.write(f"  --> Email report: sent")
                    else:
                        self.stdout.write(f"  --> Email report: skipped (email disabled or no address)")
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"  [ERROR] Email error: {e}"))
                logger.error(f"[generate_insights] Email error for {company.slug}: {e}")

        self.stdout.write(
            self.style.SUCCESS(
                f"\n[SUCCESS] Done. Insights: {total_insights} | Forecasts: {total_forecasts} | Emails: {total_emails}"
            )
        )
