#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management import BaseCommand
from gm_types.gaia import TAG_V3_TYPE

from agile.models.tag import TagMapCity, TagV3
from api.models import City


class Command(BaseCommand):
    """
    python manage.py tag_city_map
    """

    def handle(self, *args, **options):
        city_tags = TagV3.objects.using(settings.SLAVE_DB_NAME).filter(
            tag_type=TAG_V3_TYPE.CITY, is_online=True,
        ).values_list('id', 'name')
        tags_name = {item[1]: item[0] for item in city_tags}
        cities = City.objects.using(settings.SLAVE_DB_NAME).filter(
            name__in=list(tags_name.keys()), is_online=True,
        ).values_list('name', 'id')
        cities_name = {item[0]: item[1] for item in cities}

        map_list = []
        for name, c_id in cities_name.items():
            tag_id = tags_name.get(name)
            if not tag_id: continue

            map_list.append(
                TagMapCity(
                    city_id=c_id,
                    tag_id=tag_id,
                )
            )

        TagMapCity.objects.bulk_create(map_list)

        print('Done')
