Ë
    è?&j-  ã                  óX   — d Z ddlmZ dZdd„Zdd„Zdd„Zdd„Zdd„Zdd	„Z	dd
„Z
dd„Zy)u#  
services/country_utils.py
=========================
Country normalization utilities â€” public API layer over the in-memory
country snapshot.

All ORM access has been removed from this module.  Lookups are now pure
dictionary operations against the snapshot loaded at Django startup by
ServicesConfig.ready().

Public API (unchanged â€” backward compatible)
--------------------------------------------
  resolve_istat_country_code(value)  â†’ ISO3 canonical code or None
  normalize_country(value)           â†’ ISO2 code or raw fallback (ISTAT pipeline)
  is_iso2_country(value)             â†’ bool
  country_name_from_iso2(value)      â†’ display name or None
  normalize_country_fields(payload)  â†’ dict with ISO2-normalized country fields
  clear_country_cache()              â†’ no-op kept for call-site compatibility

IstatCountry schema (production)
---------------------------------
  code     â€” primary key VARCHAR(9), ISO3 alpha (e.g. "USA", "ITA")
  iso_code â€” VARCHAR(3), ISO2 (e.g. "US", "IT") or ISO3 when no ISO2
  name     â€” display name (e.g. "United States", "Italy")

Normalization contract for Alloggiati
--------------------------------------
  resolve_istat_country_code() returns IstatCountry.code (ISO3).
  normalize_country() returns ISO2 for backward compat with ISTAT pipeline.
é    )Úannotations)Úcountry_of_birthÚdocument_issuing_countryÚnationalityÚcountryc                óX   — t        | xs d«      j                  «       j                  «       S ©NÚ )ÚstrÚstripÚlower©Úvalues    ú"/backend/services/country_utils.pyÚ_normalize_keyr   .   s#   € ÜˆuŠ{˜Ó×!Ñ!Ó#×)Ñ)Ó+Ð+ó    c                ó<   — t        | xs d«      j                  «       S r	   )r   r   r   s    r   Ú_clean_valuer   2   s   € ÜˆuŠ{˜Ó×!Ñ!Ó#Ð#r   c                  ó   — y)z½
    No-op kept for call-site compatibility.

    The snapshot is now managed by services.country_snapshot.
    Use reset_country_snapshot() + load_country_snapshot() in tests instead.
    N© r   r   r   Úclear_country_cacher   :   s    r   c                ót   — t        | «      j                  «       }t        |«      dk(  xr |j                  «       S )z:Return True if value looks like a 2-letter ISO alpha code.é   )r   ÚupperÚlenÚisalpha)r   Úraws     r   Úis_iso2_countryr   C   s.   € ä
uÓ
×
#Ñ
#Ó
%€CÜˆs‹8q‰=Ò*˜SŸ[™[›]Ð*r   c                ó*   — ddl m}  || «      }|r|S dS )uò  
    Resolve any country representation to IstatCountry.code (canonical ISO3).

    Delegates to the in-memory snapshot â€” zero ORM, O(1).

    Resolution order:
      1. Empty / None                â†’ None
      2. Exact match on code (ISO3)  â†’ return code  ("USA" â†’ "USA")
      3. Match on iso_code (ISO2)    â†’ return code  ("US"  â†’ "USA")
      4. Match on country name       â†’ return code  ("Italy" â†’ "ITA")
      5. No match                    â†’ None

    Returns None (not "") to preserve the existing contract for callers
    that check `if resolve_istat_country_code(x):`.

    Args:
        value: Any country representation.

    Returns:
        IstatCountry.code string if resolved, otherwise None.
        Never raises.
    r   )Úresolve_istat_country_codeN)Úservices.country_snapshotr    )r   Ú_snap_resolveÚresults      r   r    r    I   s   € õ. Vá˜5Ó!€FÙˆ6Ð% Ð%r   c                ó  — ddl m}m}m}m}m}m} t        | «      }|sy|s |d«      ‚|j                  «       }t        |«      r|S ||v r(||   }	|j                  |	j                  «       «      }
|
r|
S t        |«      }||v r||   S |S )u  
    Normalize a country value to ISO2 for backward compatibility.

    Used by the ISTAT export pipeline and other existing callers.
    NOT used by the Alloggiati transformer (which calls resolve_istat_country_code).

    Returns ISO2 code if resolvable, otherwise the original stripped value
    (preserving existing behavior for callers that rely on the passthrough).

    Raises SnapshotNotLoadedError if the snapshot was not loaded at startup.
    This is intentional fail-fast behavior â€” no lazy loading.
    r   )ÚISO2_TO_CODEÚISO3_TO_CODEÚCODE_TO_ISO2ÚNAME_TO_ISO2Ú_snapshot_loadedÚSnapshotNotLoadedErrorNzkCountry snapshot has not been loaded. ServicesConfig.ready() must run before normalize_country() is called.)r!   r%   r&   r'   r(   r)   r*   r   r   r   Úgetr   )r   r%   r&   r'   r(   r)   r*   Ú	raw_valueÚupper_valueÚ	canonicalÚiso2Úname_keys               r   Únormalize_countryr1   f   s®   € ÷÷ ô ˜UÓ#€IÙØñ Ù$ðTó
ð 	
ð
 —/‘/Ó#€Kô {Ô#ØÐð lÑ"Ø  Ñ-ˆ	Ø×Ñ 	§¡Ó 1Ó2ˆÙØˆKô ˜iÓ(€HØ<ÑØ˜HÑ%Ð%ð Ðr   c                ó  — ddl m}m}m}m} t        | «      }|rt        |«      sy|s |d«      ‚|j                  «       }|j                  |«      }|s|S |j                  «       D ]  \  }}	|	|k(  sŒ|j                  «       c S  |S )z’Return the display name for an ISO2 code, or None if not found.

    Raises SnapshotNotLoadedError if the snapshot was not loaded at startup.
    r   )r%   ÚNAME_TO_CODEr)   r*   NzpCountry snapshot has not been loaded. ServicesConfig.ready() must run before country_name_from_iso2() is called.)r!   r%   r3   r)   r*   r1   r   r   r+   ÚitemsÚtitle)
r   r%   r3   r)   r*   Ú
normalizedÚ
iso2_upperr.   ÚnameÚcodes
             r   Úcountry_name_from_iso2r:      s›   € ÷
ó ô # 5Ó)€JÙœ_¨ZÔ8Øñ Ù$ðYó
ð 	
ð ×!Ñ!Ó#€JØ× Ñ  Ó,€IÙØÐð #×(Ñ(Ö*‰
ˆˆdØ9ÓØ—:‘:“<Òð +ð Ðr   c                ó¤   — t        | t        «      si S | j                  «       }t        D ]$  }||v sŒt	        |j                  |«      «      ||<   Œ& |S )zh
    Normalize all country fields in a payload dict to ISO2.
    Used by the ISTAT export pipeline.
    )Ú
isinstanceÚdictÚcopyÚCOUNTRY_FIELD_NAMESr1   r+   )Úpayloadr6   Ú
field_names      r   Únormalize_country_fieldsrB   Ä   sP   € ô
 gœtÔ$Øˆ	à—‘“€Jß)ˆ
Ø˜Ò#Ü%6°z·~±~ÀjÓ7QÓ%RˆJzÒ"ð *ð Ðr   N)r   ú
str | NoneÚreturnr   )rD   ÚNone)r   rC   rD   Úbool)r   rC   rD   rC   )r@   zdict | NonerD   r=   )Ú__doc__Ú
__future__r   r?   r   r   r   r   r    r1   r:   rB   r   r   r   Ú<module>rI      sA   ðñõ> #ðÐ ó,ó$óó+ó&ó:4ón$ôNr   