from django.core.management.base import BaseCommand
from exams.models import Student, DailyTask, StudentTask
from discipline.models import ClassHomeworkRecord
from academy.models import AcademyStudent
from datetime import date, timedelta

class Command(BaseCommand):
    help = 'Assigns daily Handwriting (Urdu for Morning, English for Afternoon)'

    def handle(self, *args, **options):
        today = date.today()
        tomorrow = today + timedelta(days=1)
        students = Student.objects.filter(is_active=True)
        count = 0

        for student in students:
            shift = getattr(student, 'shift', 'morning')
            subject = "Urdu Handwriting" if shift == "morning" else "English Handwriting"
            lang_flag = "Ur" if shift == "morning" else "En"

            # 1. DailyTask (For Task Hub)
            DailyTask.objects.get_or_create(
                student=student,
                date_assigned=today,
                date_due=tomorrow,
                subject=subject,
                defaults={'description': f'Practice {subject} for 15 minutes.'}
            )

            # 2. StudentTask (For Skills Page)
            StudentTask.objects.get_or_create(
                student=student,
                task_type=f"HANDWRITING_{lang_flag.upper()}",
                task_ref=f"HW-{lang_flag}-{today.strftime('%Y-%m-%d')}",
                defaults={'status': 'ASSIGNED'}
            )

            # 3. ClassHomeworkRecord (Empty record, teacher/AI will check it)
            acad_student = AcademyStudent.objects.filter(linked_code=student.code).first()
            if acad_student:
                ClassHomeworkRecord.objects.get_or_create(
                    student=acad_student,
                    date=today,
                    subject="",
                    defaults={
                        'handwriting_done': False,
                        'homework_done': False,
                        'classwork_done': False
                    }
                )
            count += 1

        self.stdout.write(self.style.SUCCESS(f'✅ Assigned Handwriting to {count} students.'))
