"""Generate daily rewards and referral commissions for active investments."""

from __future__ import annotations

from datetime import date

from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.investments.cron_tasks import CalculateRewardsTask


class Command(BaseCommand):
    help = "Calculate daily rewards (Phase 1) using the CronTask logic."

    def add_arguments(self, parser):
        parser.add_argument(
            "--date",
            type=str,
            help="ISO date (YYYY-MM-DD) to calculate. Defaults to today.",
        )

    def handle(self, *args, **options):
        target_date = self._parse_date(options.get("date"))
        
        self.stdout.write(f"Running CalculateRewardsTask for {target_date}...")
        
        task = CalculateRewardsTask(target_date)
        
        try:
            # We call execute() directly to run logic without checking cron dependency/history
            result = task.execute(target_date)
            
            if result.get("error"):
                self.stdout.write(self.style.ERROR(f"Error: {result.get('message')}"))
            else:
                self.stdout.write(self.style.SUCCESS(f"Success: {result.get('message')}"))
                self.stdout.write(self.style.WARNING(
                    "Note: This command only calculates rewards (Phase 1). "
                    "To distribute rewards (Phase 2), run the distribute-rewards task."
                ))
                
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Exception: {str(e)}"))

    def _parse_date(self, date_str: str | None) -> date:
        if date_str:
            return date.fromisoformat(date_str)
        return timezone.now().date()
