"""星之界(xzj)邀请链种子数据：自动插入组长+管事（含邀请码），无需先登录小程序。"""
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction

from jituan.models import Club, ClubHuiyuanPrice
from users.business_models import User
from users.models import UserBoss, UserGuanshi, UserZuzhang
from utils.invitationcode_utils import CreateInvitationCode

CLUB_ID = 'xzj'
WX_APPID = 'wxdefa454152e78a03'

# 固定种子账号（可重复执行，幂等）
SEED_ZUZHANG = {
    'UserUID': '9900001',
    'OpenID': 'xzj_seed_openid_zuzhang_v1',
    'Phone': '19900000001',
    'UserName': 'xzj_seed_zuzhang',
    'nickname': '星之界种子组长',
}
SEED_GUANSHI = {
    'UserUID': '9900002',
    'OpenID': 'xzj_seed_openid_guanshi_v1',
    'Phone': '19900000002',
    'UserName': 'xzj_seed_guanshi',
    'nickname': '星之界种子管事',
}


def _ensure_club():
    if Club.query.filter(club_id=CLUB_ID).exists():
        return
    call_command(
        'create_club',
        CLUB_ID,
        name='星之界电竞',
        wx_appid=WX_APPID,
    )


def _ensure_user(meta):
    user = User.query.filter(UserUID=meta['UserUID']).first()
    if not user:
        user = User.query.filter(OpenID=meta['OpenID']).first()
    if user:
        if user.ClubID != CLUB_ID:
            user.ClubID = CLUB_ID
            user.save(update_fields=['ClubID'])
        return user, False

    user = User.query.create(
        UserUID=meta['UserUID'],
        UserName=meta['UserName'],
        OpenID=meta['OpenID'],
        Phone=meta['Phone'],
        ClubID=CLUB_ID,
    )
    UserBoss.query.create(user=user, nickname=meta['nickname'])
    return user, True


def _ensure_zuzhang(user):
    if hasattr(user, 'ZuzhangProfile'):
        return user.ZuzhangProfile, False
    yaoqingma = CreateInvitationCode(str(user.UserUID))
    z = UserZuzhang.query.create(
        user=user,
        yaoqingma=yaoqingma,
        zhuangtai=1,
    )
    return z, True


def _ensure_guanshi(user, zuzhang_uid):
    if hasattr(user, 'GuanshiProfile'):
        return user.GuanshiProfile, False
    yaoqingma = CreateInvitationCode(str(user.UserUID))
    g = UserGuanshi.query.create(
        user=user,
        yaoqingma=yaoqingma,
        yaoqingren=zuzhang_uid,
        zhuangtai=1,
    )
    return g, True


class Command(BaseCommand):
    help = '插入星之界种子组长+管事（含邀请码），一条命令即可邀请注册'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force-new-codes',
            action='store_true',
            help='已存在时重新生成邀请码（慎用）',
        )

    def handle(self, *args, **options):
        with transaction.atomic():
            _ensure_club()

            zz_user, zz_new = _ensure_user(SEED_ZUZHANG)
            zz_profile, zz_profile_new = _ensure_zuzhang(zz_user)
            if options.get('force_new_codes') and not zz_profile_new:
                zz_profile.yaoqingma = CreateInvitationCode(str(zz_user.UserUID))
                zz_profile.save(update_fields=['yaoqingma'])

            gs_user, gs_new = _ensure_user(SEED_GUANSHI)
            gs_profile, gs_profile_new = _ensure_guanshi(gs_user, zz_user.UserUID)
            if options.get('force_new_codes') and not gs_profile_new:
                gs_profile.yaoqingma = CreateInvitationCode(str(gs_user.UserUID))
                gs_profile.save(update_fields=['yaoqingma'])

        price_cnt = ClubHuiyuanPrice.query.filter(club_id=CLUB_ID).count()

        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('星之界 xzj 邀请链种子数据已就绪'))
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(f'club_huiyuan_price 条数: {price_cnt}（与星阙相同则需后台 xzj 视图下单独改价）')
        self.stdout.write('')
        self.stdout.write('【组长】管事注册用这个邀请码（guanshizhuce / zuzhangyqmzc）:')
        self.stdout.write(f'  UserUID={zz_user.UserUID}  Phone={SEED_ZUZHANG["Phone"]}')
        self.stdout.write(f'  组长邀请码 inviteCode = {zz_profile.yaoqingma}')
        self.stdout.write('')
        self.stdout.write('【管事】打手注册用这个邀请码（dashouzhuce）:')
        self.stdout.write(f'  UserUID={gs_user.UserUID}  Phone={SEED_GUANSHI["Phone"]}')
        self.stdout.write(f'  管事邀请码 inviteCode = {gs_profile.yaoqingma}')
        self.stdout.write('')
        self.stdout.write('新建: 组长=%s 管事=%s' % (
            '是' if zz_new or zz_profile_new else '否（已存在）',
            '是' if gs_new or gs_profile_new else '否（已存在）',
        ))
        self.stdout.write(self.style.SUCCESS('=' * 60))
