from django.core.management.base import BaseCommand
from rog.models import GpsLog, GpsCheckin, Entry

class Command(BaseCommand):
    help = 'Debug checkin data for specific team'

    def add_arguments(self, parser):
        parser.add_argument('zekken', type=str, help='Zekken number to check')
        parser.add_argument('--event', type=str, default='岐阜ロゲイニング2025', help='Event name')

    def handle(self, *args, **options):
        zekken = options['zekken']
        event_name = options['event']
        
        self.stdout.write(f'=== Debugging checkin data for zekken {zekken}, event {event_name} ===')
        
        # Entry確認
        self.stdout.write('\n=== Entry Records ===')
        entries = Entry.objects.filter(zekken_number=int(zekken), event__event_name=event_name)
        self.stdout.write(f'Found {entries.count()} entries')
        for entry in entries:
            self.stdout.write(f'  Team: {entry.team.team_name}, Zekken: {entry.zekken_number}, Event ID: {entry.event.id}')
        
        if not entries.exists():
            self.stdout.write('❌ No entries found')
            return
        
        entry = entries.first()
        
        # GpsLog確認（文字列として検索）
        self.stdout.write('\n=== GpsLog Records (str zekken) ===')
        logs_str = GpsLog.objects.filter(zekken_number=str(zekken), event_code=event_name)
        self.stdout.write(f'Found {logs_str.count()} records in GpsLog (str)')
        for log in logs_str[:10]:
            self.stdout.write(f'  ID: {log.id}, CP: {log.cp_number}, Time: {log.checkin_time}, Event: {log.event_code}')

        # GpsLog確認（整数として検索）
        self.stdout.write('\n=== GpsLog Records (int zekken) ===')
        logs_int = GpsLog.objects.filter(zekken_number=int(zekken), event_code=event_name)
        self.stdout.write(f'Found {logs_int.count()} records in GpsLog (int)')
        for log in logs_int[:10]:
            self.stdout.write(f'  ID: {log.id}, CP: {log.cp_number}, Time: {log.checkin_time}, Event: {log.event_code}')

        # GpsCheckin確認
        self.stdout.write('\n=== GpsCheckin Records ===')
        checkins = GpsCheckin.objects.filter(zekken=str(zekken), event_code=event_name)
        self.stdout.write(f'Found {checkins.count()} records in GpsCheckin')
        for checkin in checkins[:10]:
            self.stdout.write(f'  ID: {checkin.id}, CP: {checkin.cp_number}, Time: {checkin.checkin_time}, Event: {checkin.event_code}')
        
        # 全てのGpsLogレコードから類似のものを検索
        self.stdout.write('\n=== All GpsLog Records for this event ===')
        all_logs = GpsLog.objects.filter(event_code=event_name)
        self.stdout.write(f'Total records in event: {all_logs.count()}')
        for log in all_logs[:5]:
            self.stdout.write(f'  ID: {log.id}, Zekken: {log.zekken_number} (type: {type(log.zekken_number)}), CP: {log.cp_number}, Event: {log.event_code}')
