from django.core.management.base import BaseCommand
from recruitment.models import AgencyAccessLink, AgencyJobAssignment, HiringAgency
from django.utils import timezone

class Command(BaseCommand):
    help = 'Debug agency login issues by checking existing access links'

    def handle(self, *args, **options):
        self.stdout.write("=== Agency Access Link Debug ===")

        # Check total counts
        total_links = AgencyAccessLink.objects.count()
        total_assignments = AgencyJobAssignment.objects.count()
        total_agencies = HiringAgency.objects.count()

        self.stdout.write(f"Total Access Links: {total_links}")
        self.stdout.write(f"Total Assignments: {total_assignments}")
        self.stdout.write(f"Total Agencies: {total_agencies}")
        self.stdout.write("")

        if total_links == 0:
            self.stdout.write("❌ NO ACCESS LINKS FOUND!")
            self.stdout.write("This is likely the cause of 'Invalid token or password' error.")
            self.stdout.write("")
            self.stdout.write("To fix this:")
            self.stdout.write("1. Create an agency first")
            self.stdout.write("2. Create a job assignment for the agency")
            self.stdout.write("3. Create an access link for the assignment")
            return

        # Show existing links
        self.stdout.write("📋 Existing Access Links:")
        for link in AgencyAccessLink.objects.all():
            assignment = link.assignment
            agency = assignment.agency if assignment else None
            job = assignment.job if assignment else None

            self.stdout.write(f"  📍 Token: {link.unique_token}")
            self.stdout.write(f"     Password: {link.access_password}")
            self.stdout.write(f"     Active: {link.is_active}")
            self.stdout.write(f"     Expires: {link.expires_at}")
            self.stdout.write(f"     Agency: {agency.name if agency else 'None'}")
            self.stdout.write(f"     Job: {job.title if job else 'None'}")
            self.stdout.write(f"     Valid: {link.is_valid}")
            self.stdout.write("")

        # Show assignments without links
        self.stdout.write("📋 Assignments WITHOUT Access Links:")
        assignments_without_links = AgencyJobAssignment.objects.filter(access_link__isnull=True)
        for assignment in assignments_without_links:
            self.stdout.write(f"  📍 {assignment.agency.name} - {assignment.job.title}")
            self.stdout.write(f"     Status: {assignment.status}")
            self.stdout.write(f"     Active: {assignment.is_active}")
            self.stdout.write(f"     Can Submit: {assignment.can_submit}")
            self.stdout.write("")
