import random
import names
import json
from django.core.management.base import BaseCommand
from mainapp.models import Member, Team


# TODO: refactor this file like create_teams_fixtures.py

class Command(BaseCommand):
    help = "Creates a fixture with randomly generated Member objects"

    def add_arguments(self, parser):
        parser.add_argument("num_members", type=int)

    def handle(self, *args, **options):
        num_members = options["num_members"]
        teams = Team.objects.all()
        if not teams:
            print("No teams found. Please create some teams first.")
            return

        members = []
        for team in teams:
            for _ in range(num_members):
                first_name = names.get_first_name()
                last_name = names.get_last_name()
                member = Member(first_name=first_name, last_name=last_name, team=team)
                members.append(member)

        Member.objects.bulk_create(members)

        self.stdout.write(self.style.SUCCESS(f"Created {num_members} members."))

        # create a members fixture file
        members_fixture = []
        for member in members:
            member_fixture = {
                "model": "mainapp.member",
                "pk": member.pk,
                "fields": {
                    "first_name": member.first_name,
                    "last_name": member.last_name,
                    "team": member.team_id,
                    "peg_number": member.peg_number
                }
            }
            members_fixture.append(member_fixture)

        with open("src/mainapp/fixtures/members_fixture.json", "w") as f:
            f.write(json.dumps(members_fixture, indent=2))
            self.stdout.write(self.style.SUCCESS("Created members_fixture.json."))
