from datetime import date, datetime, timedelta, timezone

from django.core.management.base import BaseCommand

from apps.charts.calc import get_element_counts, get_julian_day, get_planet_positions, set_ephe_path
from apps.charts.models import EphemerisSnapshot


class Command(BaseCommand):
    help = 'Pre-compute ephemeris snapshots for a date range (one per day at noon UTC).'

    def add_arguments(self, parser):
        parser.add_argument('--date-from', required=True, help='Start date (YYYY-MM-DD)')
        parser.add_argument('--date-to',   required=True, help='End date (YYYY-MM-DD, inclusive)')

    def handle(self, *args, **options):
        set_ephe_path()

        date_from = date.fromisoformat(options['date_from'])
        date_to   = date.fromisoformat(options['date_to'])

        current = date_from
        count = 0
        while current <= date_to:
            dt = datetime(current.year, current.month, current.day,
                          12, 0, 0, tzinfo=timezone.utc)
            jd = get_julian_day(dt)
            planets = get_planet_positions(jd)
            elements = get_element_counts(planets)

            EphemerisSnapshot.objects.update_or_create(
                dt=dt,
                defaults={
                    'fire':     elements['Fire']['count'],
                    'water':    elements['Water']['count'],
                    'earth':    elements['Earth']['count'],
                    'air':      elements['Air']['count'],
                    'time_el':  elements['Time']['count'],
                    'space_el': elements['Space']['count'],
                    'chart_data': {'planets': planets},
                },
            )
            current += timedelta(days=1)
            count += 1

        if options['verbosity'] > 0:
            self.stdout.write(
                self.style.SUCCESS(f'Created/updated {count} snapshot(s).')
            )
