"""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.
"""

from __future__ import annotations

from datetime import date
from typing import Iterable

from bookings.models import Booking
from istat.xml_export.models.c59_payload import IstatC59RowPayload
from istat.xml_export.services.c59_aggregation_service import (
    build_daily_c59_rows,
    build_daily_c59_rows_for_structure,
    resolve_c59_residence_code,
)


def _normalize_code(value: str | None) -> str:
    """Normalize a province/country code to uppercase stripped string."""
    return (value or "").strip().upper()


def _resolve_residence_code(country: str, province: str | None) -> tuple[str, str]:
    return resolve_c59_residence_code(country, province)


def build_c59_aggregation_payloads(
    bookings: Iterable[Booking],
    period_start: date,
    period_end: date,
) -> list[IstatC59RowPayload]:
    """Build 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``.
    """
    booking_list = list(bookings)
    structure = getattr(booking_list[0], "structure", None) if booking_list else None
    return build_daily_c59_rows(
        structure=structure,
        target_date=period_start,
        bookings=booking_list,
    )


def build_c59_aggregation_payloads_for_structure(
    structure_id: int,
    start_date: date,
    end_date: date,
) -> list[IstatC59RowPayload]:
    """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)
    """
    return build_daily_c59_rows_for_structure(
        structure_id=structure_id,
        target_date=start_date,
    )
