from django.core.management.base import BaseCommand
from collections import defaultdict
from stiftung.models import VierteljahresNachweis


class Command(BaseCommand):
    help = 'Check current quarterly confirmation deadline status'

    def add_arguments(self, parser):
        parser.add_argument(
            '--year',
            type=int,
            help='Check deadlines for specific year (default: current and next year)',
        )

    def handle(self, *args, **options):
        from datetime import date
        
        year_filter = options['year']
        current_year = date.today().year
        
        if year_filter:
            years_to_check = [year_filter]
        else:
            years_to_check = [current_year, current_year + 1]
        
        self.stdout.write('Current Quarterly Confirmation Deadline Status')
        self.stdout.write('=' * 50)
        
        for year in years_to_check:
            self.stdout.write(f'\nYear: {year}')
            self.stdout.write('-' * 20)
            
            deadlines_by_quarter = defaultdict(set)
            status_by_quarter = defaultdict(list)
            
            records = VierteljahresNachweis.objects.filter(jahr=year).order_by('quartal', 'destinataer__nachname')
            
            if not records:
                self.stdout.write('  No records found for this year')
                continue
                
            for record in records:
                deadlines_by_quarter[record.quartal].add(record.faelligkeitsdatum)
                status_by_quarter[record.quartal].append(record.status)
            
            # Show deadline summary
            expected_deadlines = {
                1: f'{year}-03-15',  # March 15
                2: f'{year}-06-15',  # June 15
                3: f'{year}-09-15',  # September 15
                4: f'{year}-12-15',  # December 15
            }
            
            for quarter in sorted(deadlines_by_quarter.keys()):
                unique_deadlines = list(deadlines_by_quarter[quarter])
                expected = expected_deadlines[quarter]
                record_count = len([s for s in status_by_quarter[quarter]])
                
                if len(unique_deadlines) == 1 and str(unique_deadlines[0]) == expected:
                    status_icon = self.style.SUCCESS('✓')
                    status_text = 'CORRECT'
                else:
                    status_icon = self.style.ERROR('✗')
                    status_text = 'NEEDS UPDATE'
                
                self.stdout.write(f'  Q{quarter}: {status_icon} {unique_deadlines[0]} (expected: {expected}) - {record_count} records - {status_text}')
        
        self.stdout.write('\nExpected semester-based deadline structure:')
        self.stdout.write('  Q1: March 15   (Primary semester submission)')
        self.stdout.write('  Q2: June 15    (Auto-approved when Q1 approved)')  
        self.stdout.write('  Q3: September 15 (Primary semester submission)')
        self.stdout.write('  Q4: December 15  (Auto-approved when Q3 approved)')
        
        self.stdout.write(f'\nTo update deadlines, run:')
        self.stdout.write(f'  python manage.py update_semester_deadlines --dry-run  # Preview changes')
        self.stdout.write(f'  python manage.py update_semester_deadlines           # Apply changes')