"""
Line Items Data Models

Dataclasses for line item extraction results.
"""

from dataclasses import dataclass
from decimal import Decimal, InvalidOperation


@dataclass
class LineItem:
    """Single line item from invoice."""

    row_index: int
    description: str | None = None
    quantity: str | None = None
    unit: str | None = None
    unit_price: str | None = None
    amount: str | None = None
    article_number: str | None = None
    vat_rate: str | None = None
    is_deduction: bool = False  # True if this row is a deduction/discount
    confidence: float = 0.9


@dataclass
class LineItemsResult:
    """Result of line items extraction."""

    items: list[LineItem]
    header_row: list[str]
    raw_html: str
    is_reversed: bool = False

    @property
    def total_amount(self) -> str | None:
        """Calculate total amount from line items (deduction rows have negative amounts)."""
        if not self.items:
            return None

        total = Decimal("0")
        for item in self.items:
            if item.amount:
                try:
                    # Parse Swedish number format (1 234,56)
                    amount_str = item.amount.replace(" ", "").replace(",", ".")
                    total += Decimal(amount_str)
                except InvalidOperation:
                    pass

        if total == 0:
            return None

        # Format back to Swedish format
        formatted = f"{total:,.2f}".replace(",", " ").replace(".", ",")
        # Fix the space/comma swap
        parts = formatted.rsplit(",", 1)
        if len(parts) == 2:
            return parts[0].replace(" ", " ") + "," + parts[1]
        return formatted
