import requests
from loguru import logger

from bb_integrations_lib.secrets.credential_models import TrueFillCredential


class TrueFillApiClient:
    def __init__(self, email: str, password: str, base_url: str):
        self.email = email
        self.password = password
        self.base_url = base_url
        self._token: str | None = None

    def _login(self) -> str:
        logger.info("Authenticating with TrueFill API...")
        response = requests.post(
            f"{self.base_url}/api/Account/Login",
            json={
                "email": self.email,
                "password": self.password,
                "isBuyerTPOCreated": False,
                "appType": 4,
            },
            timeout=30,
        )
        response.raise_for_status()
        data = response.json()
        if data.get("statusCode") != 0:
            raise RuntimeError(f"TrueFill login failed: {data.get('statusMessage')}")
        token = data.get("token")
        if not token:
            raise RuntimeError("TrueFill login returned no token")
        logger.info("TrueFill authentication successful")
        return token

    def _ensure_token(self):
        if self._token is None:
            self._token = self._login()

    def get_tank_readings(self) -> list[dict]:
        self._ensure_token()
        logger.info("Fetching tank readings from TrueFill API...")
        response = requests.get(
            f"{self.base_url}/api/ExchangeData/GetTankReadings",
            headers={
                "token": self._token,
                "Content-Type": "application/json",
            },
            timeout=60,
        )
        response.raise_for_status()
        data = response.json()
        if data.get("statusCode") != 0:
            raise RuntimeError(
                f"TrueFill GetTankReadings failed: {data.get('statusMessage')}"
            )
        records = data.get("responseData", [])
        logger.info(f"Retrieved {len(records)} tank readings from TrueFill")
        return records
