"""Tests for the main Contiss client."""

import os

import pytest
from pytest_httpx import HTTPXMock

from contiss import Contiss
from contiss.exceptions import AuthenticationError


def test_client_initialization_with_api_key(mock_api_key):
    """Test client initialization with API key."""
    client = Contiss(api_key=mock_api_key)
    assert client.memory is not None
    assert client.auth is not None
    client.close()


def test_client_initialization_with_token(mock_jwt_token):
    """Test client initialization with JWT token."""
    client = Contiss(token=mock_jwt_token)
    assert client.memory is not None
    assert client.auth is not None
    client.close()


def test_client_initialization_from_env(mock_api_key, monkeypatch):
    """Test client initialization from environment variable."""
    monkeypatch.setenv("CONTISS_API_KEY", mock_api_key)
    client = Contiss()
    assert client.memory is not None
    client.close()


def test_client_requires_auth():
    """Test that client requires authentication."""
    # Clear environment variable if set
    if "CONTISS_API_KEY" in os.environ:
        del os.environ["CONTISS_API_KEY"]

    with pytest.raises(ValueError, match="API key or token is required"):
        Contiss()


def test_health_check(mock_api_key, httpx_mock: HTTPXMock):
    """Test health check endpoint."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/health",
        json={"ok": True, "service": "memory-api"},
    )

    client = Contiss(api_key=mock_api_key)
    health = client.health()

    assert health.ok is True
    assert health.service == "memory-api"
    client.close()


def test_login_success(httpx_mock: HTTPXMock, mock_auth_response):
    """Test successful login."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/login", json=mock_auth_response, method="POST"
    )

    client = Contiss.login(email="test@example.com", password="password")
    assert client is not None
    client.close()


def test_login_failure(httpx_mock: HTTPXMock):
    """Test failed login."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/login",
        status_code=401,
        json={"error": "unauthorized", "message": "Invalid credentials"},
        method="POST",
    )

    with pytest.raises(AuthenticationError):
        Contiss.login(email="test@example.com", password="wrong_password")


def test_register_success(httpx_mock: HTTPXMock, mock_auth_response):
    """Test successful registration."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/auth/register", json=mock_auth_response, method="POST"
    )

    client = Contiss.register(
        email="new@example.com",
        password="secure_password",
        org_name="New Company",
        name="New User",
    )
    assert client is not None
    client.close()


def test_context_manager(mock_api_key):
    """Test using client as context manager."""
    with Contiss(api_key=mock_api_key) as client:
        assert client.memory is not None
        assert client.auth is not None


def test_custom_base_url(mock_api_key):
    """Test client with custom base URL."""
    client = Contiss(api_key=mock_api_key, base_url="http://localhost:8080")
    assert client._http_client.base_url == "http://localhost:8080"
    client.close()


def test_custom_timeout(mock_api_key):
    """Test client with custom timeout."""
    client = Contiss(api_key=mock_api_key, timeout=60.0)
    assert client._http_client.timeout == 60.0
    client.close()
