"""
TroncoCorp SDK — Python client for the TroncoCorp ecosystem API.

Requires: requests (pip install requests)

Usage:
    from troncocorp import TroncoCorpSDK

    sdk = TroncoCorpSDK()
    ecosystem = sdk.get_ecosystem()
    for entity in ecosystem["entities"]:
        print(entity["name"], entity["status"])
"""

from __future__ import annotations

import json
from typing import Any, Optional


class TroncoCorpSDK:
    """Client for the TroncoCorp public API.

    Args:
        base_url: Root URL of the TroncoCorp API.
            Defaults to ``https://troncocorp.es``.
    """

    def __init__(self, base_url: str = "https://troncocorp.es") -> None:
        self.base_url = base_url.rstrip("/")
        self._session: Optional[Any] = None

    @property
    def _requests(self) -> Any:
        """Lazy-import ``requests`` so the SDK can be imported without it."""
        import requests as _req

        return _req

    def _get(self, path: str) -> dict[str, Any]:
        """Internal GET request helper."""
        import requests as req

        url = f"{self.base_url}{path}"
        resp = req.get(url, headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
        }, timeout=15)
        resp.raise_for_status()
        return resp.json()

    def get_ecosystem(self) -> dict[str, Any]:
        """Fetch the full ecosystem data: entities, divisions, timeline, metrics.

        Returns:
            dict with keys: ``ecosystem``, ``entities``, ``divisions``,
            ``timeline``, ``metrics``.

        Example:
            >>> eco = sdk.get_ecosystem()
            >>> len(eco["entities"])
            12
        """
        return self._get("/api/ecosystem")

    def get_status(self) -> dict[str, Any]:
        """Get live health status of TroncoCorp sites.

        Returns:
            dict with keys: ``ecosystem``, ``generatedAt``, ``summary``,
            ``sites``.

        Example:
            >>> status = sdk.get_status()
            >>> status["summary"]["allOperational"]
            True
        """
        return self._get("/api/status")

    def get_entity(self, name: str) -> Optional[dict[str, Any]]:
        """Get a specific entity by its slug/id from the ecosystem.

        Args:
            name: Entity slug (e.g. ``'zenit'``, ``'tripx'``).

        Returns:
            The entity dict or ``None`` if not found.

        Example:
            >>> zenit = sdk.get_entity("zenit")
            >>> zenit["name"]
            'Zénit'
        """
        eco = self.get_ecosystem()
        for e in eco["entities"]:
            if e["id"] == name or e["name"].lower() == name.lower():
                return e
        return None

    def get_metrics(self) -> dict[str, Any]:
        """Get growth metrics from the ecosystem data.

        Returns:
            dict with keys: ``growthByYear``, ``capitalization``,
            ``activeUsers``, ``transactions``.

        Example:
            >>> metrics = sdk.get_metrics()
            >>> metrics["growthByYear"][0]["year"]
            2025
        """
        eco = self.get_ecosystem()
        return eco["metrics"]
