from __future__ import annotations

import json

from pydantic import field_validator
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    model_config = {"env_prefix": "AEGRO_"}

    farms: dict[str, str] = {}
    aegro_api_base_url: str = "https://app.aegro.com.br"
    api_timeout: float = 30.0
    api_max_retries: int = 3
    log_level: str = "INFO"

    @field_validator("farms", mode="before")
    @classmethod
    def parse_farms_json(cls, v):
        if isinstance(v, str):
            return json.loads(v)
        return v

    def masked_farms(self) -> dict[str, str]:
        return {
            name: f"***...{key[-3:]}" if len(key) > 3 else "***" for name, key in self.farms.items()
        }

    def farm_names(self) -> list[str]:
        return sorted(self.farms.keys())

    def get_api_key(self, farm_name: str) -> str | None:
        return self.farms.get(farm_name)
