from __future__ import annotations

import logging
from typing import Any, Dict

import httpx

from core.config import settings

logger = logging.getLogger(__name__)


class DodaExternalService:
    """
    Cliente HTTP para el servicio externo de alta DODA (API de Ventanilla Única).

    Endpoints:
      POST {base_url}/api/v1/doda/alta
      GET  {base_url}/api/v1/doda/alta-status/{task_id}
      POST {base_url}/api/v1/doda/consulta
      GET  {base_url}/api/v1/doda/consulta-status/{task_id}
      POST {base_url}/api/v1/doda/eliminar
      GET  {base_url}/api/v1/doda/eliminar-status/{task_id}

    Usa COVE_API_URL como URL base (la misma variable que COVE y Expediente).
    """

    def __init__(self) -> None:
        self.base_url = settings.COVE_API_URL.strip()
        self.verify_ssl = settings.COVE_API_VERIFY_SSL

    def post_alta(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """
        Envía el payload de alta DODA al servicio externo.
        Retorna {task_id, status, message}.
        """
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/alta"

        configuracion_vu = payload.get("configuracion_vu") or {}
        logger.info(
            "Enviando alta DODA: rfc_ciec=%s cer_len=%s key_len=%s clave_fiel_len=%s",
            configuracion_vu.get("rfc_ciec"),
            len(configuracion_vu.get("archivo_cer_base64") or ""),
            len(configuracion_vu.get("archivo_key_base64") or ""),
            len(configuracion_vu.get("clave_fiel") or ""),
        )

        with httpx.Client(
            timeout=httpx.Timeout(60.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.post(url, json=payload)
            response.raise_for_status()
            return response.json()

    def get_status(self, task_id: str) -> Dict[str, Any]:
        """
        Consulta el estado de una tarea de alta DODA en el servicio externo.
        """
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/alta-status/{task_id}"
        logger.debug("Consultando estado tarea DODA: task_id=%s url=%s", task_id, url)

        with httpx.Client(
            timeout=httpx.Timeout(30.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.get(url)
            response.raise_for_status()
            return response.json()

    def post_consulta(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Envia consulta DODA y retorna {task_id, status, message}."""
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/consulta"
        with httpx.Client(
            timeout=httpx.Timeout(60.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.post(url, json=payload)
            response.raise_for_status()
            return response.json()

    def get_consulta_status(self, task_id: str) -> Dict[str, Any]:
        """Consulta el estado de una tarea de consulta DODA."""
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/consulta-status/{task_id}"
        with httpx.Client(
            timeout=httpx.Timeout(30.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.get(url)
            response.raise_for_status()
            return response.json()

    def post_eliminar(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Envia eliminacion DODA y retorna {task_id, status, message}."""
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/eliminar"
        with httpx.Client(
            timeout=httpx.Timeout(60.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.post(url, json=payload)
            response.raise_for_status()
            return response.json()

    def get_eliminar_status(self, task_id: str) -> Dict[str, Any]:
        """Consulta el estado de una tarea de eliminacion DODA."""
        url = f"{self.base_url.rstrip('/')}/api/v1/doda/eliminar-status/{task_id}"
        with httpx.Client(
            timeout=httpx.Timeout(30.0, connect=10.0), verify=self.verify_ssl
        ) as client:
            response = client.get(url)
            response.raise_for_status()
            return response.json()
