"""Obol client - main entry point for SDK."""
import os
from typing import Optional

from obol.api import ObolAPI
from obol.session import ObolSession


class Obol:
    """Trust infrastructure for AI agents.

    Usage:
        obol = Obol(api_key="ob_live_xxx")
        agent = obol.register("my-agent")

        with obol.session(agent) as session:
            # All operations tracked
            do_stuff()
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
    ):
        self.api_key = api_key or os.environ.get("OBOL_API_KEY")
        if not self.api_key:
            raise ValueError(
                "Obol API key required. Pass api_key= or set OBOL_API_KEY env var."
            )

        self.base_url = base_url or os.environ.get(
            "OBOL_API_URL", "https://obol.grayowlresearch.com/v1"
        )
        self._api = ObolAPI(self.api_key, self.base_url)
        self._policies = {}

    def register(
        self,
        name: str,
        model: Optional[str] = None,
        framework: Optional[str] = None,
        capabilities: Optional[list[str]] = None,
        metadata: Optional[dict] = None,
    ) -> dict:
        """Register a new agent for trust tracking.

        Returns agent dict with 'id', 'name', 'trust', etc.
        """
        return self._api.register_agent(
            name=name,
            model=model,
            framework=framework,
            capabilities=capabilities or [],
            metadata=metadata or {},
        )

    def session(self, agent: dict, **kwargs) -> "ObolSession":
        """Create a tracked session for an agent.

        Usage:
            with obol.session(agent) as session:
                # All file/network/process ops are tracked
                ...
        """
        return ObolSession(
            api=self._api,
            agent=agent,
            policies=self._policies,
            **kwargs,
        )

    def record(
        self,
        agent: dict,
        action: str,
        target: Optional[str] = None,
        result: str = "success",
        duration_ms: Optional[int] = None,
        session_id: Optional[str] = None,
        **kwargs,
    ) -> dict:
        """Manually record a single event."""
        import uuid
        return self._api.record_event(
            agent_id=agent["id"],
            session_id=session_id or str(uuid.uuid4()),
            action=action,
            target=target,
            result=result,
            duration_ms=duration_ms,
            **kwargs,
        )

    def score(self, agent: dict) -> dict:
        """Get current trust score for an agent."""
        return self._api.get_score(agent["id"])

    def can(self, agent: dict, action: str, resource: str) -> bool:
        """Check if agent has enough trust to access a resource."""
        result = self._api.check_access(agent["id"], action, resource)
        return result.get("allowed", False)

    def policy(self, agent: dict, policies: dict):
        """Set access policies.

        policies = {
            "file_write:/home/sensitive/*": {"min_trust": 90},
            "send_email": {"min_trust": 85, "action": "block"},
        }
        """
        for resource, config in policies.items():
            self._api.create_policy(
                resource=resource,
                min_trust=config.get("min_trust", 50),
                min_tier=config.get("min_tier", "trusted"),
                action=config.get("action", "block"),
            )

    def start(self, name: str, **kwargs) -> "ObolSession":
        """Quick start: register agent and begin a tracked session.

        This is the simplest way to instrument an agent:

            import obol
            session = obol.start("my-agent")
            # ... your agent code ...
            session.end()

        Returns an active ObolSession (already entered).
        """
        agent = self.register(name, **kwargs)
        session = self.session(agent)
        session.__enter__()
        return session

    def agents(self) -> list[dict]:
        """List all registered agents."""
        result = self._api.list_agents()
        return result.get("agents", [])

    def compliance(self) -> dict:
        """Get compliance status summary."""
        return self._api.get_compliance_status()

    def compliance_report(self, regulation: Optional[str] = None) -> dict:
        """Get compliance report, optionally for a single regulation."""
        return self._api.get_compliance_report(slug=regulation)
