"""Normalize CFTC ZIP archives to gzip CSV."""

import gzip
import zipfile
from io import BytesIO


def find_csv_inner_filename(buffer: BytesIO) -> str:
    """Find the single .txt file inside a CFTC ZIP archive.

    CFTC uses .txt extension for their comma-delimited CSV files. The filename
    varies across years (e.g. 'f_year.txt', 'FUT_DISAGG_2015.txt'). We assert
    exactly one .txt file exists and return its name.
    """
    with zipfile.ZipFile(buffer, mode="r") as zf:
        txt_files = [n for n in zf.namelist() if n.lower().endswith(".txt")]
        assert len(txt_files) == 1, (
            f"Expected exactly 1 .txt file in CFTC ZIP, found: {zf.namelist()}"
        )
        return txt_files[0]


def normalize_zipped_csv(buffer: BytesIO, inner_filename: str) -> BytesIO:
    """Extract a single CSV from a ZIP and recompress as gzip.

    Args:
        buffer: ZIP file content as BytesIO (will be read from position 0).
        inner_filename: Name of the file inside the ZIP archive.

    Returns:
        BytesIO with gzip-compressed CSV content, seeked to position 0.
    """
    buffer.seek(0)
    out = BytesIO()
    with zipfile.ZipFile(buffer, mode="r") as zf:
        assert inner_filename in zf.namelist(), (
            f"Expected '{inner_filename}' in ZIP, found: {zf.namelist()}"
        )
        with zf.open(inner_filename, mode="r") as csv_file:
            with gzip.open(out, "wb") as gz:
                gz.write(csv_file.read())
    out.seek(0)
    return out
