from django.core.management.base import BaseCommand

from ats.services import process_application_scoring
from jobs.models import JobApplication


class Command(BaseCommand):
    help = 'Re-analyze all candidate content and recompute match scores for every application'

    def handle(self, *args, **options):
        total = 0
        updated = 0
        analyzed = 0
        for application in JobApplication.objects.select_related(
            'job', 'applicant', 'applicant__seeker_profile',
        ).iterator():
            total += 1
            had_content = bool(application.cv_parsed_text)
            old_score = application.match_score
            process_application_scoring(application, parse_content=True)
            if application.cv_parsed_text and not had_content:
                analyzed += 1
            if application.match_score != old_score:
                updated += 1
        self.stdout.write(
            self.style.SUCCESS(
                f'Processed {total} application(s): '
                f'{analyzed} newly analyzed, {updated} score(s) updated.'
            )
        )
