import json
from datetime import datetime, UTC
from io import BytesIO

import pandas as pd
from loguru import logger

from bb_integrations_lib.models.rita.config import FileConfig
from bb_integrations_lib.protocols.pipelines import Step
from bb_integrations_lib.provider.api.truefill.client import TrueFillApiClient
from bb_integrations_lib.shared.model import FileConfigRawData


class TrueFillTankReadingsStep(Step[None, FileConfigRawData]):
    def __init__(self, truefill_client: TrueFillApiClient, fc: FileConfig, tenant_name: str = "TrueFill", *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.truefill_client = truefill_client
        self.fc = fc
        self.tenant_name = tenant_name

    def describe(self) -> str:
        return f"Pull tank readings from TrueFill API ({self.tenant_name})"

    async def execute(self, _) -> FileConfigRawData:
        records = self.truefill_client.get_tank_readings()
        if not records:
            raise ValueError("TrueFill API returned no tank readings")

        logger.info(f"Converting {len(records)} records to CSV")
        self.pipeline_context.included_files[f"{self.tenant_name} TrueFill Inventory"] = json.dumps(records)

        df = pd.DataFrame.from_records(records)
        csv_string = df.to_csv(index=False)
        return FileConfigRawData(
            file_name=f"{self.tenant_name.lower().replace(' ', '_')}_truefill_readings_{datetime.now(UTC)}.csv",
            data=BytesIO(csv_string.encode("utf-8")),
            file_config=self.fc,
            data_buffer_bkp=csv_string,
        )
