"""Main Contiss client."""

import os
from typing import Optional

from ._http import HTTPClient
from .resources import AuthResource, MemoryResource
from .types import AuthResponse, HealthCheck


class Contiss:
    """Contiss AI SDK client.

    The main entry point for interacting with the Contiss API.

    Args:
        api_key: API key for authentication (starts with sk_live_)
        token: JWT token for authentication (alternative to api_key)
        base_url: Base URL for the API (defaults to production)
        timeout: Request timeout in seconds
        max_retries: Maximum number of retries for failed requests

    Example:
        ```python
        from contiss import Contiss

        # Initialize with API key
        client = Contiss(api_key="sk_live_...")

        # Or with environment variable
        # export CONTISS_API_KEY="sk_live_..."
        client = Contiss()

        # Write a memory
        memory = client.memory.write(
            org_id="org_uuid",
            project_id="proj_uuid",
            content="User prefers dark mode"
        )
        ```
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        token: Optional[str] = None,
        base_url: str = "https://api.contiss.ai",
        timeout: float = 30.0,
        max_retries: int = 3,
    ) -> None:
        """Initialize the Contiss client."""
        # Try to get API key from environment if not provided
        if not api_key and not token:
            api_key = os.getenv("CONTISS_API_KEY")

        if not api_key and not token:
            raise ValueError(
                "API key or token is required. "
                "Set CONTISS_API_KEY environment variable or pass api_key parameter."
            )

        # Initialize HTTP client
        self._http_client = HTTPClient(
            base_url=base_url,
            api_key=api_key,
            token=token,
            timeout=timeout,
            max_retries=max_retries,
        )

        # Initialize resources
        self.auth = AuthResource(self._http_client)
        self.memory = MemoryResource(self._http_client)

    def health(self) -> HealthCheck:
        """Check API health status.

        Returns:
            HealthCheck object with status information

        Example:
            ```python
            health = client.health()
            print(f"API is {'up' if health.ok else 'down'}")
            ```
        """
        response = self._http_client.get("/health")
        return HealthCheck(**response)

    @classmethod
    def login(cls, email: str, password: str, base_url: str = "https://api.contiss.ai") -> "Contiss":
        """Login with email and password to get a JWT token.

        Args:
            email: User email
            password: User password
            base_url: Base URL for the API

        Returns:
            Contiss client initialized with JWT token

        Raises:
            AuthenticationError: If credentials are invalid

        Example:
            ```python
            client = Contiss.login(
                email="user@example.com",
                password="secure_password"
            )
            ```
        """
        # Create temporary client without auth to make login request
        temp_client = HTTPClient(base_url=base_url, timeout=30.0, max_retries=3)
        try:
            response = temp_client.post("/auth/login", json={"email": email, "password": password})
            auth_response = AuthResponse(**response)
        finally:
            temp_client.close()

        # Return new client with token
        return cls(token=auth_response.token, base_url=base_url)

    @classmethod
    def register(
        cls,
        email: str,
        password: str,
        org_name: str,
        name: Optional[str] = None,
        base_url: str = "https://api.contiss.ai",
    ) -> "Contiss":
        """Register a new user and organization.

        Args:
            email: User email
            password: User password (min 8 characters)
            org_name: Name for the new organization
            name: Optional display name for the user
            base_url: Base URL for the API

        Returns:
            Contiss client initialized with JWT token

        Raises:
            ValidationError: If parameters are invalid
            ConflictError: If user already exists

        Example:
            ```python
            client = Contiss.register(
                email="user@example.com",
                password="secure_password",
                org_name="My Company",
                name="John Doe"
            )
            ```
        """
        # Create temporary client without auth to make registration request
        temp_client = HTTPClient(base_url=base_url, timeout=30.0, max_retries=3)
        try:
            payload = {
                "email": email,
                "password": password,
                "org_name": org_name,
            }
            if name:
                payload["name"] = name

            response = temp_client.post("/auth/register", json=payload)
            auth_response = AuthResponse(**response)
        finally:
            temp_client.close()

        # Return new client with token
        return cls(token=auth_response.token, base_url=base_url)

    def close(self) -> None:
        """Close the HTTP client and clean up resources."""
        self._http_client.close()

    def __enter__(self) -> "Contiss":
        """Context manager entry."""
        return self

    def __exit__(self, *args: object) -> None:
        """Context manager exit."""
        self.close()
