"""XLS file format detection and row extraction.

Handles OLE2/BIFF .xls files (the format ICE uses for all reports).
Format detection via magic bytes — no extension sniffing.
"""

import xlrd

OLE2_MAGIC = b"\xd0\xcf\x11\xe0"
XLSX_MAGIC = b"PK\x03\x04"


def detect_file_format(content_bytes: bytes) -> str:
    """Return 'xls', 'xlsx', 'csv', or 'html' based on magic bytes/content."""
    assert content_bytes, "content_bytes must not be empty"

    if content_bytes[:4] == OLE2_MAGIC:
        return "xls"
    if content_bytes[:4] == XLSX_MAGIC:
        return "xlsx"
    # Sniff text-based formats
    sample = content_bytes[:512].decode("utf-8", errors="replace").lstrip()
    if sample.startswith("<"):
        return "html"
    return "csv"


def xls_to_rows(content_bytes: bytes, sheet_index: int = 0) -> list[list]:
    """Parse XLS bytes and return sheet rows as list of lists.

    Values are returned as Python types (str, int, float, datetime, bool).
    Empty cells become empty string "".
    """
    assert content_bytes, "content_bytes must not be empty"
    assert content_bytes[:4] == OLE2_MAGIC, (
        f"Not an OLE2/BIFF XLS file (magic: {content_bytes[:4].hex()})"
    )

    book = xlrd.open_workbook(file_contents=content_bytes)
    assert sheet_index < book.nsheets, (
        f"sheet_index {sheet_index} out of range (nsheets={book.nsheets})"
    )
    sheet = book.sheets()[sheet_index]

    rows = []
    for row_idx in range(sheet.nrows):
        row = []
        for col_idx in range(sheet.ncols):
            cell = sheet.cell(row_idx, col_idx)
            if cell.ctype == xlrd.XL_CELL_EMPTY:
                row.append("")
            elif cell.ctype == xlrd.XL_CELL_DATE:
                # Keep as raw serial — callers convert with xlrd.xldate_as_datetime
                row.append(cell.value)
            else:
                row.append(cell.value)
        rows.append(row)

    return rows
