#/apps/aroflo_connector_app/config.py
from dataclasses import dataclass
import os
from typing import Mapping


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_credentials(cls, credentials: Mapping[str, str]) -> "AroFloSettings":
        """Build tenant-scoped settings from values resolved by the platform vault."""
        required = (
            "aroflo_base_url",
            "aroflo_u_encoded",
            "aroflo_p_encoded",
            "aroflo_api_secret",
            "aroflo_org_encoded",
        )
        missing = [name for name in required if not str(credentials.get(name) or "").strip()]
        if missing:
            raise AroFloConfigError("Required AroFlo API credentials are not configured.")

        try:
            timeout = int(credentials.get("aroflo_timeout") or 20)
        except (TypeError, ValueError) as exc:
            raise AroFloConfigError("AroFlo timeout must be an integer.") from exc

        return cls(
            base_url=str(credentials["aroflo_base_url"]).strip(),
            u_encoded=str(credentials["aroflo_u_encoded"]).strip(),
            p_encoded=str(credentials["aroflo_p_encoded"]).strip(),
            api_secret=str(credentials["aroflo_api_secret"]),
            org_encoded=str(credentials["aroflo_org_encoded"]).strip(),
            accept=str(credentials.get("aroflo_accept") or "text/json").strip(),
            host_ip=str(credentials.get("aroflo_host_ip") or "").strip(),
            timeout=max(1, min(timeout, 60)),
        )

    @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")),
        )
