"""A role's country, from its places, else from the one its host states.""" from __future__ import annotations from collections.abc import Iterable from app import places def of_host(gaz: places.Gazetteer, stated: str) -> str | None: """The ISO code a host's country names, in the host's spelling: a code ("DK", "dk"), or a name the gazetteer has as an alias of a country ("Denmark", "Danmark"), `EU` or Europe by name, or a text that resolves to places of one country. '' for nothing stated, None for a text naming no country.""" text = (stated or "").strip() if not text: return "" if ("country", text.upper()) in gaz.by_key or text.upper() == "EU": return text.upper() named = {"EU" if gaz.places[p].key == "europe" else gaz.places[p].key for p in gaz.aliases.get(places.fold(text), ()) if gaz.places[p].kind == "country" or (gaz.places[p].kind, gaz.places[p].key) == ("continent", "europe")} if len(named) == 1: return named.pop() found = {gaz.country(p) for p in gaz.resolve(text)} - {""} return found.pop() if len(found) == 1 else None def _in_europe(gaz: places.Gazetteer, code: str) -> bool: if code == "EU": return True europe = gaz.by_key.get(("continent", "europe")) place_id = gaz.by_key.get(("country", code)) return europe is not None and place_id is not None and europe in gaz.ancestors(place_id) def country(gaz: places.Gazetteer, place_ids: Iterable[int], host_country: str = "") -> str: """The one country the role's resolved places lie in, continents aside; Europe alone is `EU`; else, when they lie in several all in Europe, `EU` (what `country_of` wrote for "Dublin, London" and the country gate reads as Europe); else the host's stated country (`of_host`); else ''.""" ids = list(place_ids) # A continent beside a country is the wider unit a line adds ("Home # based - EMEA; London" is GB), as `country_of` had it; alone, Europe # is `EU`. found = {gaz.country(p) for p in ids} - {""} if not found and any(gaz.places[p].key == "europe" for p in ids if p in gaz.places): found = {"EU"} if len(found) == 1: return found.pop() if len(found) > 1 and all(_in_europe(gaz, code) for code in found): return "EU" return of_host(gaz, host_country) or ""