
    `jN	                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZ ddZdd	Z	 	 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 	 	 ddZy)aO  C59 aggregation builder for Liguria ISTAT XML export.

Transforms guest-night level data into aggregated C59 rows grouped by residence
(Italian province or foreign country) for daily movement reporting.

This module is fully isolated under xml_export/ and does not modify any existing
TXT export, old ISTAT services, or API endpoints.
    )annotations)date)Iterable)Booking)IstatC59RowPayload)build_daily_c59_rows"build_daily_c59_rows_for_structureresolve_c59_residence_codec                F    | xs dj                         j                         S )z?Normalize a province/country code to uppercase stripped string. )stripupper)values    =/backend/istat/xml_export/builders/c59_aggregation_builder.py_normalize_coder      s    KR &&((    c                    t        | |      S )N)r
   )countryprovinces     r   _resolve_residence_coder      s    %gx88r   c                \    t        |       }|rt        |d   dd      nd}t        |||      S )zBuild daily C59 rows for the requested day.

    C59 files are daily. ``period_end`` is accepted for backward-compatible
    callers, but aggregation is intentionally performed for ``period_start``.
    r   	structureN)r   target_datebookings)listgetattrr   )r   period_start
period_endbooking_listr   s        r   build_c59_aggregation_payloadsr    !   s:     >L?KQd;QUI  r   c                    t        | |      S )a  Build C59 aggregation payloads for a specific structure and date range.
    
    Convenience wrapper that fetches bookings for the structure and delegates
    to build_c59_aggregation_payloads.
    
    Args:
        structure_id: ID of the Structure to report on
        start_date: Start date (inclusive) for reporting period
        end_date: End date (inclusive) for reporting period
        
    Returns:
        List of IstatC59RowPayload sorted by (nazione, residenza)
    )structure_idr   )r	   )r"   
start_dateend_dates      r   ,build_c59_aggregation_payloads_for_structurer%   4   s    $ .! r   N)r   
str | Nonereturnstr)r   r(   r   r&   r'   ztuple[str, str])r   zIterable[Booking]r   r   r   r   r'   list[IstatC59RowPayload])r"   intr#   r   r$   r   r'   r)   )__doc__
__future__r   datetimer   typingr   bookings.modelsr   #istat.xml_export.models.c59_payloadr   1istat.xml_export.services.c59_aggregation_servicer   r	   r
   r   r   r    r%    r   r   <module>r3      s    #   # B )
9  	&  	r   