import polars as pl
from dateutil.parser import parse


def format_date(dt: str) -> str:
    return parse(dt).strftime("%m/%d/%Y %H:%M")


class CircleKReadingParser:
    """Circle K format parser with TelaPoint integration fields."""

    def parse(self, df: pl.DataFrame) -> pl.DataFrame:
        rows = []
        for record in df.to_dicts():
            rows.append(
                {
                    "ClientName": None,
                    "FacilityName": None,
                    "FacilityInternalID": None,
                    "FacilityState": None,
                    "VolumePercentage": None,
                    "TankStatus": None,
                    "TankNbr": None,
                    "TankInternalID": None,
                    "AtgTankNumber": record["Tank Id"],
                    "ATGTankLabel": None,
                    "Product": None,
                    "TankCapacity": None,
                    "Ullage": None,
                    "SafeUllage": None,
                    "Volume": record["Volume"],
                    "Height": None,
                    "Water": None,
                    "Temperature": None,
                    "InventoryDate": format_date(record["Read Time"]),
                    "SystemUnits": None,
                    "CollectionDateTimeUtc": None,
                    "TelaPointAccountNumber": 100814,
                    "TelaPointSiteNumber": record["Store Number"],
                }
            )

        return pl.DataFrame(rows)


class CircleK2ReadingParser:
    """Simplified Circle K format for Gravitate system integration."""

    def parse(self, df: pl.DataFrame) -> pl.DataFrame:
        rows = []
        for record in df.to_dicts():
            rows.append(
                {
                    "storeNumber": record.get("Store Source Number"),
                    "timestamp": format_date(record["Read Time"]),
                    "tankLabel": record.get("Tank Product"),
                    "volume": record["Volume"],
                    "tankNumber": record["Tank Id"],
                    "ullage": record.get("Ullage", 0),
                    "productLevel": 0,
                    "waterLevel": 0,
                    "temperature": 0,
                }
            )

        return pl.DataFrame(rows)
