"""Exact credit parsing and formatting helpers.

Credits are user-facing TFLOP values, but the ledger stores integer subunits so
settlement stays exact and avoids float drift.
"""

from __future__ import annotations

from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

CREDIT_DECIMAL_PLACES = 6
CREDIT_SUBUNITS_PER_CREDIT = 1_000_000
_CREDIT_SCALE = Decimal(CREDIT_SUBUNITS_PER_CREDIT)
_CREDIT_QUANTUM = Decimal("0.000001")


def parse_credit_amount_to_subunits(value: str | int | float | Decimal) -> int:
    """Parse a TFLOP credit amount into exact integer ledger subunits."""
    try:
        decimal_value = Decimal(str(value)).quantize(
            _CREDIT_QUANTUM,
            rounding=ROUND_HALF_UP,
        )
    except (InvalidOperation, ValueError) as exc:
        raise ValueError(f"Invalid credit amount: {value}") from exc

    if decimal_value <= 0:
        raise ValueError("Credit amount must be positive")

    return int((decimal_value * _CREDIT_SCALE).to_integral_value())


def credit_subunits_to_decimal(value: int | float | Decimal) -> Decimal:
    """Convert integer ledger subunits into a TFLOP credit value."""
    return Decimal(str(value)) / _CREDIT_SCALE


def format_credit_subunits(value: int | float | Decimal, places: int = 6) -> str:
    """Format raw credit subunits as a trimmed TFLOP credit string."""
    quantized = credit_subunits_to_decimal(value).quantize(
        Decimal(1).scaleb(-places),
        rounding=ROUND_HALF_UP,
    )
    text = format(quantized, "f")
    return text.rstrip("0").rstrip(".") or "0"
