from django.core.management.base import BaseCommand
from django.test import Client
from django.contrib.auth import get_user_model
from django.utils import timezone
from exams.models import Student, StudentTask, HealthScore, KnowledgeComponent
from discipline.models import DisciplineLedger, ClassHomeworkRecord
from academy.models import AcademyStudent
import uuid

class Command(BaseCommand):
    help = 'ISO/IEC/IEEE 29119-4 Functional E2E Completeness Audit'

    def handle(self, *args, **kwargs):
        self.stdout.write(self.style.MIGRATE_HEADING("\n=== FUNCTIONAL COMPLETENESS AUDIT ===\n"))
        c = Client()
        admin = get_user_model().objects.filter(is_superuser=True).first()
        c.force_login(admin)

        results = []
        
        # TEST 1: Handwriting Points Routing (9th Grade)
        s9 = Student.objects.filter(student_class__startswith='9').first()
        if s9:
            acc_s9 = AcademyStudent.objects.filter(code=s9.code).first()
            if acc_s9:
                ClassHomeworkRecord.objects.filter(student=acc_s9, date=timezone.now().date()).delete()
                
                hs, _ = HealthScore.objects.get_or_create(student=s9)
                old_score = hs.score
                url = '/discipline/class-homework/save/'
                c.post(url, {
                    'date': timezone.now().date().isoformat(),
                    f's_{acc_s9.id}_present': '1',
                    f's_{acc_s9.id}_hw_en': '1',
                    f's_{acc_s9.id}_hw_ur': '1',
                    f's_{acc_s9.id}_star': '5'
                }, secure=True)
                hs.refresh_from_db()
                if hs.score > old_score:
                    results.append(('Handwriting -> Mizan (9th)', 'PASS', f'Score {old_score} -> {hs.score}'))
                else:
                    results.append(('Handwriting -> Mizan (9th)', 'FAIL', 'Score did not update'))

        # TEST 2: Handwriting Points Routing (Non-9th Grade)
        s_other = Student.objects.exclude(student_class__startswith='9').first()
        if s_other:
            acc_other = AcademyStudent.objects.filter(code=s_other.code).first()
            if acc_other:
                ClassHomeworkRecord.objects.filter(student=acc_other, date=timezone.now().date()).delete()
                
                old_count = DisciplineLedger.objects.filter(student=acc_other).count()
                url = '/discipline/class-homework/save/'
                c.post(url, {
                    'date': timezone.now().date().isoformat(),
                    f's_{acc_other.id}_present': '1',
                    f's_{acc_other.id}_hw_en': '1',
                    f's_{acc_other.id}_star': '5'
                }, secure=True)
                new_count = DisciplineLedger.objects.filter(student=acc_other).count()
                if new_count > old_count:
                    results.append(('Handwriting -> Discipline (Other)', 'PASS', f'Ledger rows {old_count} -> {new_count}'))
                else:
                    results.append(('Handwriting -> Discipline (Other)', 'FAIL', 'No ledger created'))

        # TEST 3: Direct Task Assignment
        s9 = Student.objects.filter(student_class__startswith='9').first()
        kc = KnowledgeComponent.objects.filter(is_active=True).first()
        if s9 and kc:
            url = '/api/portal/teacher/tasks/'
            initial_tasks = StudentTask.objects.filter(student=s9).count()
            unique_ref = f"TEST-{uuid.uuid4().hex[:6]}"
            
            resp = c.post(url, {
                'action': 'direct_assign',
                'task_type': 'KC_DISCOVERY',
                'task_refs': unique_ref,
                'student_codes': s9.code
            }, follow=True, secure=True)
            
            new_tasks = StudentTask.objects.filter(student=s9).count()
            if new_tasks > initial_tasks:
                results.append(('Task Assignment (Direct)', 'PASS', 'Task created in DB'))
            else:
                msgs = [str(m) for m in resp.context['messages']] if resp.context and 'messages' in resp.context else []
                results.append(('Task Assignment (Direct)', 'FAIL', f'Unchanged. Msgs: {msgs}'))

        self.generate_report(results)

    def generate_report(self, results):
        self.stdout.write(f"{'FUNCTIONAL TEST':<40} | {'STATUS':<8} | {'DETAILS'}")
        self.stdout.write("-" * 80)
        passes = 0
        for r in results:
            color = self.style.SUCCESS if r[1] == 'PASS' else self.style.ERROR
            if r[1] == 'PASS': passes += 1
            self.stdout.write(f"{r[0]:<40} | {color(r[1]):<8} | {r[2]}")
        self.stdout.write("-" * 80)
        self.stdout.write(f"\nTotal: {len(results)} | PASS: {passes} | FAIL: {len(results)-passes}\n")
