from dataclasses import dataclass
import os


class AroFloConfigError(RuntimeError):
    """Error de configuración de la app Aroflo."""


@dataclass
class AroFloSettings:
    base_url: str
    u_encoded: str
    p_encoded: str
    api_secret: str
    org_encoded: str
    accept: str
    host_ip: str
    timeout: int = 30

    @classmethod
    def from_env(cls) -> "AroFloSettings":
        """
        Carga la configuración desde variables de entorno.

        Obligatorias:
          - AROFLO_BASE_URL
          - AROFLO_UENCODED
          - AROFLO_PENCODED
          - AROFLO_API_SECRET
          - AROFLO_ORG_ENCODED
        Opcionales:
          - AROFLO_ACCEPT (text/json por defecto)
          - AROFLO_HOST_IP
          - AROFLO_TIMEOUT
        """
        required = [
            "AROFLO_BASE_URL",
            "AROFLO_UENCODED",
            "AROFLO_PENCODED",
            "AROFLO_API_SECRET",
            "AROFLO_ORG_ENCODED",
        ]
        missing = [v for v in required if os.getenv(v) is None]
        if missing:
            raise AroFloConfigError(
                f"Faltan variables de entorno para AroFlo: {', '.join(missing)}"
            )

        return cls(
            base_url=os.getenv("AROFLO_BASE_URL"),
            u_encoded=os.getenv("AROFLO_UENCODED"),
            p_encoded=os.getenv("AROFLO_PENCODED"),
            api_secret=os.getenv("AROFLO_API_SECRET"),
            org_encoded=os.getenv("AROFLO_ORG_ENCODED"),
            accept=os.getenv("AROFLO_ACCEPT", "text/json"),
            host_ip=os.getenv("AROFLO_HOST_IP", ""),
            timeout=int(os.getenv("AROFLO_TIMEOUT", "30")),
        )
