from django.core.management.base import BaseCommand
from django.utils import timezone
from device_interaction.models import DeviceType, DeviceBatch, Device, UserDevice
from userapp.models import ParadiseUser

FALLBACK_MAC = '00:55:11:44:f3:22'


class Command(BaseCommand):
    help = '创建 Unity Editor 测试用兜底设备（MAC: 00:55:11:44:f3:22）并绑定到指定用户'

    def add_arguments(self, parser):
        parser.add_argument(
            '--username',
            type=str,
            default='',
            help='绑定到哪个用户（username），不填则自动选第一个超级管理员'
        )

    def handle(self, *args, **options):
        # 1. 找用户
        username = options['username']
        if username:
            try:
                user = ParadiseUser.objects.get(username=username)
            except ParadiseUser.DoesNotExist:
                self.stdout.write(self.style.ERROR(f'用户 "{username}" 不存在'))
                return
        else:
            user = ParadiseUser.objects.filter(is_superuser=True).first()
            if not user:
                user = ParadiseUser.objects.first()
            if not user:
                self.stdout.write(self.style.ERROR('数据库中没有任何用户，请先创建用户'))
                return
        self.stdout.write(f'绑定目标用户: {user.username} (id={user.id})')

        # 2. 获取或创建设备类型
        device_type, created = DeviceType.objects.get_or_create(
            code='T01',
            defaults={
                'name': '测试设备类型',
                'description': 'Unity Editor 本地测试用'
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'创建设备类型: {device_type.name} (T01)'))
        else:
            self.stdout.write(f'使用已有设备类型: {device_type.name} (T01)')

        # 3. 获取或创建批次
        batch, created = DeviceBatch.objects.get_or_create(
            batch_number='BT01-TEST',
            defaults={
                'device_type': device_type,
                'production_date': timezone.now().date(),
                'quantity': 1,
                'description': 'Unity Editor 测试批次'
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'创建批次: {batch.batch_number}'))
        else:
            self.stdout.write(f'使用已有批次: {batch.batch_number}')

        # 4. 获取或创建设备
        device, created = Device.objects.get_or_create(
            mac_address=FALLBACK_MAC,
            defaults={
                'device_type': device_type,
                'batch': batch,
                'serial_number': 'TEST-001',
                'is_active': True,
                'activated_at': timezone.now(),
            }
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'创建设备: {device.device_code} (MAC: {FALLBACK_MAC})'))
        else:
            self.stdout.write(f'设备已存在: {device.device_code} (MAC: {FALLBACK_MAC})')
            # 确保已激活
            if not device.is_active:
                device.is_active = True
                device.activated_at = timezone.now()
                device.save()
                self.stdout.write(self.style.SUCCESS('设备已更新为激活状态'))

        # 5. 绑定用户
        user_device, created = UserDevice.objects.get_or_create(
            user=user,
            device=device,
            defaults={'nickname': 'Editor测试设备', 'is_primary': True}
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'设备已绑定到用户 {user.username}'))
        else:
            self.stdout.write(f'设备已绑定过用户 {user.username}，跳过')

        self.stdout.write(self.style.SUCCESS(
            f'\n完成！现在可以用以下地址测试：\n'
            f'https://qy-lty.airlabs.art/api/device/rtc-token/get_by_mac/?mac_address={FALLBACK_MAC}'
        ))
