from django.db import migrations


def seed(apps, schema_editor):
    from taxonomy.data import INDUSTRY_ALIASES, TAXONOMY

    Industry = apps.get_model('taxonomy', 'Industry')
    SubIndustry = apps.get_model('taxonomy', 'SubIndustry')
    IndustryAlias = apps.get_model('taxonomy', 'IndustryAlias')

    for order, (industry_name, subs) in enumerate(TAXONOMY.items()):
        industry, _ = Industry.objects.get_or_create(name=industry_name, defaults={
            'slug': industry_name.lower().replace(' ', '-').replace(',', '').replace('&', 'and').replace('/', '-'),
            'sort_order': order,
        })
        for sub_order, sub_name in enumerate(subs):
            slug = f'{industry.pk}-{sub_name}'.lower().replace(' ', '-').replace(',', '').replace('&', 'and').replace('/', '-')
            SubIndustry.objects.get_or_create(industry=industry, name=sub_name, defaults={
                'slug': slug[:170], 'sort_order': sub_order,
            })

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


def unseed(apps, schema_editor):
    apps.get_model('taxonomy', 'Industry').objects.all().delete()


class Migration(migrations.Migration):
    dependencies = [('taxonomy', '0001_initial')]
    operations = [migrations.RunPython(seed, unseed)]
