# Path: matcher/model.py
# class IsA(Base):
#     __tablename__ = 'isa'
#     item_id = Column(Integer, primary_key=True, autoincrement=False)
#     entity = Column(postgresql.JSON)
#     qid = column_property('Q' + cast(item_id, String))
#     label = Column(String)
# 
#     def __repr__(self):
#         return f'<matcher.model.IsA object: {self.qid}>'
# 
#     def url(self):
#         return f'https://www.wikidata.org/wiki/Q{self.item_id}'
# 
#     def label_best_language(self, languages, plural=False):
#         if not self.entity:
#             return
# 
#         labels = self.entity['labels']
#         for lang in languages:
#             code = lang if isinstance(lang, str) else lang.wikimedia_language_code
#             if code in labels:
#                 if plural:
#                     return utils.pluralize_label(labels[code])
#                 else:
#                     return labels[code]['value']
# 
#         if plural and 'en' in labels:
#             return utils.pluralize_label(labels['en'])
# 
#         return self.entity_label()
# 
#     def label_and_description_list(self, want_languages):
#         language_codes = {l.wikimedia_language_code for l in want_languages}
#         try:
#             labels = self.entity['labels']
#         except (TypeError, KeyError):
#             return []
#         descriptions = self.entity['descriptions']
# 
#         ret = {}
#         for lang, label in labels.items():
#             if lang not in language_codes:
#                 continue
#             description = descriptions[lang]['value'] if lang in descriptions else None
#             ret[lang] = {'label': label['value'], 'description': description}
#         return ret
# 
#     def label_and_description(self, languages):
#         try:
#             labels = self.entity['labels']
#         except (TypeError, KeyError):
#             return {'lang': None, 'label': None, 'description': None}
#         descriptions = self.entity['descriptions']
#         for lang in languages:
#             code = lang.wikimedia_language_code
#             if code not in labels:
#                 continue
# 
#             description = descriptions[code]['value'] if code in descriptions else None
#             return {
#                 'lang': lang,
#                 'label': labels[code]['value'],
#                 'description': description,
#             }
#         return {'lang': None, 'label': None, 'description': None}
# 
#     def entity_label(self, lang='en'):
#         labels = self.entity['labels']
#         if lang in labels:
#             return labels[lang]['value']
#         elif 'en' in labels:
#             return labels['en']['value']
#         elif labels:
#             return list(labels.values())[0]['value']
# 
#     def label_and_qid(self):
#         if self.entity and 'labels' not in self.entity:
#             subject = f'missing labels: {self.qid}'
#             body = f'Wikidata entity is missing labels\n\n{self.url}'
#             mail.send_mail(subject, body)
#             return self.qid
#         else:
#             return f'{self.entity_label()} ({self.qid})'
# 
#     def labels(self):
#         return self.entity['labels']
# 
# class ItemIsA(Base):
#     __tablename__ = 'item_isa'
#     item_id = Column(Integer, ForeignKey('item.item_id'), primary_key=True)
#     isa_id = Column(Integer, ForeignKey('isa.item_id'), primary_key=True)
# 
#     item = relationship('Item')
#     isa = relationship('IsA')


import json
from .model import IsA, ItemIsA

    isa_fields = ["item_id", "entity", "qid", "label"]

    place_data = {key: getattr(place, key) for key in place_fields}

    place_data["added"] = str(place.added)
    place_data["geom"] = json.loads(place.geojson)

    isa_list = []

    item_list = []
    item_map = {}
    item_ids = []
    for item in place.get_candidate_items():
        item_ids.append(item.item_id)

        item_data = {key: getattr(item, key) for key in item_fields}
        item_data["lat"], item_data["lon"] = item.get_lat_lon()
        item_data["tags"] = list(item.tags)
        item_data["extracts"] = dict(item.extracts)
        item_data["candidates"] = []
        item_data["isa"] = []
        for candidate in item.candidates:
            candidate_data = {key: getattr(candidate, key) for key in candidate_fields}
            candidate_data["geom"] = json.loads(place.geojson)
            item_data["candidates"].append(candidate_data)

        item_map[item.item_id] = item_data
        item_list.append(item_data)


# Path: matcher/model.py
# class IsA(Base):
#     __tablename__ = 'isa'
#     item_id = Column(Integer, primary_key=True, autoincrement=False)
#     entity = Column(postgresql.JSON)
#     qid = column_property('Q' + cast(item_id, String))
#     label = Column(String)
# 
#     def __repr__(self):
#         return f'<matcher.model.IsA object: {self.qid}>'
# 
#     def url(self):
#         return f'https://www.wikidata.org/wiki/Q{self.item_id}'
# 
#     def label_best_language(self, languages, plural=False):
#         if not self.entity:
#             return
# 
#         labels = self.entity['labels']
#         for lang in languages:
#             code = lang if isinstance(lang, str) else lang.wikimedia_language_code
#             if code in labels:
#                 if plural:
#                     return utils.pluralize_label(labels[code])
#                 else:
#                     return labels[code]['value']
# 
#         if plural and 'en' in labels:
#             return utils.pluralize_label(labels['en'])
# 
#         return self.entity_label()
# 
#     def label_and_description_list(self, want_languages):
#         language_codes = {l.wikimedia_language_code for l in want_languages}
#         try:
#             labels = self.entity['labels']
#         except (TypeError, KeyError):
#             return []
#         descriptions = self.entity['descriptions']
# 
#         ret = {}
#         for lang, label in labels.items():
#             if lang not in language_codes:
#                 continue
#             description = descriptions[lang]['value'] if lang in descriptions else None
#             ret[lang] = {'label': label['value'], 'description': description}
#         return ret
# 
#     def label_and_description(self, languages):
#         try:
#             labels = self.entity['labels']
#         except (TypeError, KeyError):
#             return {'lang': None, 'label': None, 'description': None}
#         descriptions = self.entity['descriptions']
#         for lang in languages:
#             code = lang.wikimedia_language_code
#             if code not in labels:
#                 continue
# 
#             description = descriptions[code]['value'] if code in descriptions else None
#             return {
#                 'lang': lang,
#                 'label': labels[code]['value'],
#                 'description': description,
#             }
#         return {'lang': None, 'label': None, 'description': None}
# 
#     def entity_label(self, lang='en'):
#         labels = self.entity['labels']
#         if lang in labels:
#             return labels[lang]['value']
#         elif 'en' in labels:
#             return labels['en']['value']
#         elif labels:
#             return list(labels.values())[0]['value']
# 
#     def label_and_qid(self):
#         if self.entity and 'labels' not in self.entity:
#             subject = f'missing labels: {self.qid}'
#             body = f'Wikidata entity is missing labels\n\n{self.url}'
#             mail.send_mail(subject, body)
#             return self.qid
#         else:
#             return f'{self.entity_label()} ({self.qid})'
# 
#     def labels(self):
#         return self.entity['labels']
# 
# class ItemIsA(Base):
#     __tablename__ = 'item_isa'
#     item_id = Column(Integer, ForeignKey('item.item_id'), primary_key=True)
#     isa_id = Column(Integer, ForeignKey('isa.item_id'), primary_key=True)
# 
#     item = relationship('Item')
#     isa = relationship('IsA')


# Path: matcher/export.py
import json
from .model import IsA, ItemIsA


    isa_fields = ["item_id", "entity", "qid", "label"]

    place_data = {key: getattr(place, key) for key in place_fields}

    place_data["added"] = str(place.added)
    place_data["geom"] = json.loads(place.geojson)

    isa_list = []

    item_list = []
    item_map = {}
    item_ids = []
    for item in place.get_candidate_items():
        item_ids.append(item.item_id)

        item_data = {key: getattr(item, key) for key in item_fields}
        item_data["lat"], item_data["lon"] = item.get_lat_lon()
        item_data["tags"] = list(item.tags)
        item_data["extracts"] = dict(item.extracts)
        item_data["candidates"] = []
        item_data["isa"] = []
        for candidate in item.candidates:
            candidate_data = {key: getattr(candidate, key) for key in candidate_fields}
            candidate_data["geom"] = json.loads(place.geojson)
            item_data["candidates"].append(candidate_data)

        item_map[item.item_id] = item_data
        item_list.append(item_data)


    q = IsA.query.join(ItemIsA).filter(ItemIsA.item_id.in_(item_ids))