from django.core.management.base import BaseCommand
from django.db import transaction

from taxonomy.data import INDUSTRY_ALIASES, TAXONOMY
from taxonomy.helpers import clear_cache
from taxonomy.models import Industry, IndustryAlias, SubIndustry


class Command(BaseCommand):
    help = 'Seed (or refresh) the master industry/sub-industry taxonomy from taxonomy/data.py. Safe to re-run.'

    @transaction.atomic
    def handle(self, *args, **options):
        industries_created = sub_created = aliases_created = 0

        for order, (industry_name, subs) in enumerate(TAXONOMY.items()):
            industry, created = Industry.objects.get_or_create(name=industry_name, defaults={'sort_order': order})
            if created:
                industries_created += 1
            elif industry.sort_order != order:
                industry.sort_order = order
                industry.save(update_fields=['sort_order'])

            for sub_order, sub_name in enumerate(subs):
                _sub, sub_new = SubIndustry.objects.get_or_create(
                    industry=industry, name=sub_name, defaults={'sort_order': sub_order})
                if sub_new:
                    sub_created += 1

        for industry_name, aliases in INDUSTRY_ALIASES.items():
            industry = Industry.objects.filter(name=industry_name).first()
            if not industry:
                continue
            for term in aliases:
                _alias, alias_new = IndustryAlias.objects.get_or_create(term=term, defaults={'industry': industry})
                if alias_new:
                    aliases_created += 1

        clear_cache()
        self.stdout.write(self.style.SUCCESS(
            f'Industries: {Industry.objects.count()} ({industries_created} new). '
            f'Sub-industries: {SubIndustry.objects.count()} ({sub_created} new). '
            f'Aliases: {IndustryAlias.objects.count()} ({aliases_created} new).'
        ))
