"""CausewayClient — Python SDK for interacting with the iKnowhy API."""
from typing import Optional

import httpx


class CausewayClient:
    """
    Lightweight SDK client for iKnowhy.

    Usage::

        client = CausewayClient(api_key="cwy_...")
        event_id = client.log("tool_call", payload={"tool": "browser"}, session_id="sess1")
        chain = client.chain(event_id)
        violations = client.violations()
    """

    def __init__(self, api_key: str, base_url: str = "https://iknowhy.ai"):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.headers = {"Authorization": f"Bearer {api_key}"}

    def log(
        self,
        name: str,
        payload: Optional[dict] = None,
        session_id: Optional[str] = None,
        cause_ids: Optional[list] = None,
        tags: Optional[dict] = None,
    ) -> str:
        """Log a causal event. Returns the new event_id."""
        body = {
            "name": name,
            "payload": payload or {},
            "session_id": session_id,
            "cause_ids": cause_ids or [],
            "tags": tags or {},
        }
        resp = httpx.post(
            f"{self.base_url}/api/events",
            json=body,
            headers=self.headers,
            timeout=10.0,
        )
        resp.raise_for_status()
        return resp.json()["event_id"]

    def chain(self, event_id: str) -> list:
        """Return the full causal ancestry chain for an event."""
        resp = httpx.get(
            f"{self.base_url}/api/chain/{event_id}",
            headers=self.headers,
            timeout=10.0,
        )
        resp.raise_for_status()
        return resp.json()["chain"]

    def violations(self) -> list:
        """Return current constraint violations."""
        resp = httpx.get(
            f"{self.base_url}/api/violations",
            headers=self.headers,
            timeout=10.0,
        )
        resp.raise_for_status()
        return resp.json()["violations"]

    def sessions(self) -> list:
        """Return list of sessions."""
        resp = httpx.get(
            f"{self.base_url}/api/sessions",
            headers=self.headers,
            timeout=10.0,
        )
        resp.raise_for_status()
        return resp.json()["sessions"]

    def events(
        self,
        session_id: Optional[str] = None,
        name: Optional[str] = None,
        limit: int = 100,
    ) -> list:
        """Return events with optional filters."""
        params = {"limit": limit}
        if session_id:
            params["session_id"] = session_id
        if name:
            params["name"] = name
        resp = httpx.get(
            f"{self.base_url}/api/events",
            headers=self.headers,
            params=params,
            timeout=10.0,
        )
        resp.raise_for_status()
        return resp.json()["events"]
