"""Shared helpers for ODE assessment performance denominators.

ODE's reported achievement percentages use the sum of the four performance
level counts, which can be smaller than ``Number of Participants``.  Keep the
derived denominator explicit so downstream code does not have to rediscover
that distinction independently.

This module is imported by ETL/report code; it has no command-line entry point
or file I/O. Decimal arithmetic preserves CSV count precision. Blank, suppressed,
negative, or incomplete level counts cannot produce a denominator; callers must
handle None rather than substituting participation counts or zero."""

from __future__ import annotations

from decimal import Decimal, InvalidOperation
from typing import Iterable, Mapping, MutableMapping, Sequence


SCORED_PERFORMANCE_DENOMINATOR_FIELD = "Scored Performance Denominator"
LEVEL_COUNT_FIELDS = (
    "Number Level 1",
    "Number Level 2",
    "Number Level 3",
    "Number Level 4",
)


def parse_decimal(value: object) -> Decimal | None:
    """Return a finite decimal for a CSV value, or ``None`` when suppressed."""

    if value is None:
        return None
    text = str(value).strip().replace(",", "")
    if not text:
        return None
    try:
        value_decimal = Decimal(text)
    except InvalidOperation:
        return None
    return value_decimal if value_decimal.is_finite() else None


def format_count(value: Decimal | None) -> str:
    """Format an ODE count without adding an unnecessary decimal suffix."""

    if value is None:
        return ""
    integral = value.to_integral_value()
    if value == integral:
        return str(integral)
    return format(value.normalize(), "f")


def derive_scored_performance_denominator(row: Mapping[str, object]) -> Decimal | None:
    """Sum Level 1-4 counts when all four counts are available and nonnegative."""

    values = [parse_decimal(row.get(field)) for field in LEVEL_COUNT_FIELDS]
    if any(value is None or value < 0 for value in values):
        return None
    total = sum(values, Decimal("0"))
    return total if total > 0 else None


def populate_scored_performance_denominator(row: MutableMapping[str, object]) -> Decimal | None:
    """Set the stored denominator on a row and return its numeric value."""

    denominator = derive_scored_performance_denominator(row)
    row[SCORED_PERFORMANCE_DENOMINATOR_FIELD] = format_count(denominator)
    return denominator


def insert_field_after(
    header: Sequence[str],
    field: str,
    after_field: str,
) -> list[str]:
    """Return a header containing ``field`` immediately after ``after_field``."""

    output = [item for item in header if item != field]
    try:
        index = output.index(after_field) + 1
    except ValueError as exc:
        raise ValueError(f"Required column {after_field!r} is missing") from exc
    return output[:index] + [field] + output[index:]


def add_scored_performance_denominator_column(
    header: Sequence[str],
    rows: Iterable[Sequence[object]],
) -> tuple[list[str], list[list[object]]]:
    """Add or refresh the stored denominator in list-based CSV rows."""

    original_header = list(header)
    output_header = insert_field_after(
        original_header,
        SCORED_PERFORMANCE_DENOMINATOR_FIELD,
        "Number of Participants",
    )
    output_rows: list[list[object]] = []
    for values in rows:
        row = {
            field: values[index] if index < len(values) else ""
            for index, field in enumerate(original_header)
        }
        populate_scored_performance_denominator(row)
        output_rows.append([row.get(field, "") for field in output_header])
    return output_header, output_rows
