"""FoundryMatch SaaS API helpers for g-gremlin."""

from __future__ import annotations

import os
from typing import Any, Dict, Optional

import click

from g_gremlin.base import (
    AuthenticationError,
    BaseIntegration,
    IntegrationError,
    RateLimitError,
    RetryConfig,
    TransientError,
)
from g_gremlin.credentials import resolve_credentials
from g_gremlin.credentials.provider import CredentialProvider, SecretNotFoundError

DEFAULT_API_BASE = os.getenv("G_GREMLIN_FM_API_BASE") or os.getenv("FOUNDRYOPS_API_URL") or "https://api.foundryops.io"


class FoundryMatchError(RuntimeError):
    """Raised when FoundryMatch SaaS operations fail."""


class FoundryMatchAuthError(FoundryMatchError):
    """Raised when FoundryMatch credentials are invalid."""


class FoundryMatchClient(BaseIntegration):
    """Client for FoundryMatch SaaS enrichment endpoints."""

    SERVICE_NAME = "foundrymatch"

    def __init__(
        self,
        api_base: Optional[str] = None,
        api_key: Optional[str] = None,
        workspace_id: Optional[str] = None,
        credential_provider: Optional[CredentialProvider] = None,
        retry_config: Optional[RetryConfig] = None,
    ) -> None:
        super().__init__(
            credential_provider=credential_provider,
            default_retry_config=retry_config or RetryConfig(),
        )
        creds = None
        if not api_key or not api_base or not workspace_id:
            try:
                creds = resolve_credentials(
                    "foundrymatch",
                    required_keys=["api_base", "api_key", "workspace_id"],
                    credential_provider=credential_provider,
                )
            except SecretNotFoundError:
                creds = None
        self.api_base = (api_base or (creds or {}).get("api_base") or DEFAULT_API_BASE).rstrip("/")
        self.api_key = api_key or (creds or {}).get("api_key")
        self.workspace_id = workspace_id or (creds or {}).get("workspace_id")
        if not self.api_key or not self.workspace_id:
            raise click.ClickException(
                "FoundryMatch SaaS credentials not configured. "
                "Set G_GREMLIN_FM_API_BASE, G_GREMLIN_FM_API_KEY, and G_GREMLIN_FM_WORKSPACE_ID "
                "or run g-gremlin auth set foundrymatch."
            )

    def _headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

    def _url(self, path: str) -> str:
        path = path if path.startswith("/") else f"/{path}"
        return f"{self.api_base}{path}"

    def run_enrichment(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        try:
            resp = self._post(self._url("/api/v1/enrichment/run"), headers=self._headers(), json=payload)
            return resp.json()
        except AuthenticationError as exc:
            raise FoundryMatchAuthError("FoundryMatch API key invalid.") from exc
        except (RateLimitError, IntegrationError, TransientError) as exc:
            raise FoundryMatchError(str(exc)) from exc

    def get_job_status(self, job_id: str) -> Dict[str, Any]:
        try:
            resp = self._get(self._url(f"/api/v1/enrichment/run/{job_id}"), headers=self._headers())
            return resp.json()
        except AuthenticationError as exc:
            raise FoundryMatchAuthError("FoundryMatch API key invalid.") from exc
        except (RateLimitError, IntegrationError, TransientError) as exc:
            raise FoundryMatchError(str(exc)) from exc
