"""
CSV POS parser — parses POS export files into transaction records.

Expected CSV format (semicolon or comma separated):
    timestamp;nozzle_nama;plat_nomor;jenis_kendaraan;volume;nilai

Header row is auto-detected and skipped. Separator is auto-detected.
"""

import csv
import io
from datetime import datetime
from decimal import Decimal, InvalidOperation
from typing import Any


def parse_pos_csv(raw: str) -> list[dict[str, Any]]:
    """
    Parse raw CSV text into a list of transaction dicts.

    Returns list of:
        {
            "timestamp": datetime | None,
            "nozzle_nama": str | None,
            "plat_nomor": str | None,
            "jenis_kendaraan": str | None,
            "volume": Decimal,
            "nilai": Decimal,
        }
    """
    lines = raw.strip().split("\n")
    if not lines:
        raise ValueError("File CSV kosong")

    # Auto-detect separator
    sep = ";" if ";" in lines[0] else ","

    reader = csv.reader(io.StringIO(raw.strip()), delimiter=sep)
    rows = list(reader)

    if len(rows) < 2:
        raise ValueError("File CSV harus memiliki minimal 1 baris data")

    # Skip header row (first row)
    header = [h.strip().lower() for h in rows[0]]
    data_rows = rows[1:]

    results: list[dict[str, Any]] = []

    for i, row in enumerate(data_rows, start=2):
        if len(row) < 4:
            continue  # skip incomplete rows

        try:
            # Try to map by header if recognized
            record = _parse_row_by_position(row)
            results.append(record)
        except (ValueError, InvalidOperation) as e:
            # Skip malformed rows silently
            continue

    if not results:
        raise ValueError("Tidak ada data valid dalam file CSV")

    return results


def _parse_row_by_position(row: list[str]) -> dict[str, Any]:
    """Parse a CSV row by positional columns."""
    # Expected order: timestamp, nozzle_nama, plat_nomor, jenis_kendaraan, volume, nilai
    timestamp_str = row[0].strip() if len(row) > 0 else ""
    nozzle_nama = row[1].strip() if len(row) > 1 else None
    plat_nomor = row[2].strip() if len(row) > 2 else None
    jenis_kendaraan = row[3].strip() if len(row) > 3 else None
    volume_str = row[4].strip() if len(row) > 4 else "0"
    nilai_str = row[5].strip() if len(row) > 5 else "0"

    # Parse timestamp
    ts = None
    if timestamp_str:
        for fmt in ("%Y-%m-%d %H:%M:%S", "%d/%m/%Y %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%d-%m-%Y %H:%M:%S"):
            try:
                ts = datetime.strptime(timestamp_str, fmt)
                break
            except ValueError:
                continue

    volume = Decimal(volume_str.replace(",", ".")) if volume_str else Decimal("0")
    nilai = Decimal(nilai_str.replace(",", ".")) if nilai_str else Decimal("0")

    return {
        "timestamp": ts,
        "nozzle_nama": nozzle_nama or None,
        "plat_nomor": plat_nomor or None,
        "jenis_kendaraan": jenis_kendaraan or None,
        "volume": volume,
        "nilai": nilai,
    }
