from __future__ import annotations

"""Nexure SDK client — the public interface.

Usage:
    from nexure import Nexure

    nx = Nexure(api_key="nx_live_...")
    record = nx.decisions.record(
        decision_type="credit_underwriting",
        evidence={"fico_score": 711},
        action="approve",
        decided_by="reviewer_schen",
    )
"""

import os

import httpx

from nexure.exceptions import NexureError
from nexure.resources.analytics import AnalyticsResource
from nexure.resources.anomalies import AnomaliesResource
from nexure.resources.api_keys import ApiKeysResource
from nexure.resources.briefs import BriefsResource
from nexure.resources.decisions import DecisionsResource
from nexure.resources.explanations import ExplanationsResource
from nexure.resources.ledger import LedgerResource
from nexure.resources.outcomes import OutcomesResource
from nexure.resources.packages import PackagesResource
from nexure.resources.templates import TemplatesResource

DEFAULT_BASE_URL = "https://api.nexuredata.com/v1"


class Nexure:
    """Nexure SDK client.

    Args:
        api_key: API key (or set NEXURE_API_KEY env var)
        base_url: API base URL (or set NEXURE_API_BASE_URL env var)
        timeout: Request timeout in seconds (default 30)
    """

    def __init__(
        self,
        api_key: str | None = None,
        base_url: str | None = None,
        timeout: float = 30.0,
    ):
        self.api_key = api_key or os.environ.get("NEXURE_API_KEY")
        if not self.api_key:
            raise NexureError(
                "API key is required. Pass api_key= or set NEXURE_API_KEY environment variable."
            )

        self.base_url = base_url or os.environ.get("NEXURE_API_BASE_URL") or DEFAULT_BASE_URL

        self._client = httpx.Client(
            base_url=self.base_url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
                "User-Agent": "nexure-python/0.1.0",
            },
            timeout=timeout,
        )

        # Resource namespaces
        self.decisions = DecisionsResource(self._client)
        self.packages = PackagesResource(self._client)
        self.ledger = LedgerResource(self._client)
        self.briefs = BriefsResource(self._client)
        self.analytics = AnalyticsResource(self._client)
        self.anomalies = AnomaliesResource(self._client)
        self.outcomes = OutcomesResource(self._client)
        self.explanations = ExplanationsResource(self._client)
        self.templates = TemplatesResource(self._client)
        self.api_keys = ApiKeysResource(self._client)

    def close(self) -> None:
        """Close the HTTP client."""
        self._client.close()

    def __enter__(self) -> Nexure:
        return self

    def __exit__(self, *args) -> None:
        self.close()
