"""Prepare generated XML as download-ready in-memory export results."""

from __future__ import annotations

from datetime import datetime

from django.utils import timezone

from istat.xml_export.models.export_result import IstatXmlExportResult


ISTAT_XML_CONTENT_TYPE = "application/xml; charset=utf-8"


def encode_xml_content(content: str) -> bytes:
    """Encode XML content using the export layer's canonical encoding."""

    return content.encode("utf-8")


def calculate_utf8_byte_size(content: str) -> int:
    """Return the UTF-8 byte size for XML content."""

    return len(encode_xml_content(content))


def build_xml_export_result(
    *,
    filename: str,
    content: str,
    generated_at: datetime | None = None,
    content_type: str = ISTAT_XML_CONTENT_TYPE,
) -> IstatXmlExportResult:
    """Create the standardized immutable export result."""

    return IstatXmlExportResult(
        filename=filename,
        content=content,
        content_type=content_type,
        generated_at=generated_at or timezone.now(),
        byte_size=calculate_utf8_byte_size(content),
    )
