"""Tests for memory resource."""

import pytest
from pytest_httpx import HTTPXMock

from contiss import Contiss
from contiss.exceptions import AuthenticationError, NotFoundError, ValidationError


def test_write_memory(
    mock_api_key, mock_org_id, mock_project_id, mock_memory_response, httpx_mock: HTTPXMock
):
    """Test writing a memory."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write", json=mock_memory_response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    result = client.memory.write(
        org_id=mock_org_id,
        project_id=mock_project_id,
        content="Test memory content",
        type="fact",
    )

    assert result.id == "mem_abc123"
    assert result.version == 1
    assert result.is_current is True
    client.close()


def test_write_memory_with_all_params(
    mock_api_key, mock_org_id, mock_project_id, mock_memory_response, httpx_mock: HTTPXMock
):
    """Test writing a memory with all parameters."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write", json=mock_memory_response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    result = client.memory.write(
        org_id=mock_org_id,
        project_id=mock_project_id,
        content="Test memory",
        type="decision",
        title="Test Title",
        tags=["tag1", "tag2"],
        confidence=0.9,
        requires_review=True,
    )

    assert result.id is not None
    client.close()


def test_write_memory_with_supersedes(
    mock_api_key, mock_org_id, mock_project_id, httpx_mock: HTTPXMock
):
    """Test writing a memory that supersedes another."""
    response = {
        "id": "mem_new123",
        "root_id": "mem_abc123",
        "version": 2,
        "is_current": True,
        "requires_review": False,
        "type": "fact",
    }

    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write", json=response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    result = client.memory.write(
        org_id=mock_org_id,
        project_id=mock_project_id,
        content="Updated memory",
        supersedes_id="mem_abc123",
    )

    assert result.version == 2
    assert result.root_id == "mem_abc123"
    client.close()


def test_search_memories(
    mock_api_key, mock_org_id, mock_project_id, mock_search_response, httpx_mock: HTTPXMock
):
    """Test searching memories."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/search", json=mock_search_response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    results = client.memory.search(
        org_id=mock_org_id, project_id=mock_project_id, query="user preferences"
    )

    assert len(results.items) == 1
    assert results.items[0].content == "User prefers dark mode"
    assert results.items[0].similarity == 0.95
    client.close()


def test_search_with_filters(
    mock_api_key, mock_org_id, mock_project_id, mock_search_response, httpx_mock: HTTPXMock
):
    """Test searching with filters."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/search", json=mock_search_response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    results = client.memory.search(
        org_id=mock_org_id,
        project_id=mock_project_id,
        query="test query",
        limit=5,
        types=["fact", "decision"],
        tags=["important"],
        search_mode="semantic",
    )

    assert len(results.items) >= 0
    client.close()


def test_bundle_memories(
    mock_api_key, mock_org_id, mock_project_id, httpx_mock: HTTPXMock
):
    """Test getting memory bundle."""
    bundle_response = {
        "project_id": mock_project_id,
        "task": "Build profile page",
        "summary": "User prefers dark mode and large fonts",
        "items": [
            {
                "id": "mem_abc123",
                "project_id": mock_project_id,
                "type": "fact",
                "title": "UI Preference",
                "content": "User prefers dark mode",
                "tags": ["ui"],
                "sources": [],
                "confidence": 0.9,
                "requires_review": False,
                "root_id": None,
                "version": 1,
                "is_current": True,
                "created_by": "user_123",
                "created_at": "2026-01-02T10:00:00Z",
                "updated_at": "2026-01-02T10:00:00Z",
            }
        ],
        "total_items": 1,
        "total_chars": 24,
        "truncated": False,
    }

    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/bundle", json=bundle_response, method="POST"
    )

    client = Contiss(api_key=mock_api_key)
    bundle = client.memory.bundle(
        org_id=mock_org_id,
        project_id=mock_project_id,
        task="Build profile page",
        max_items=10,
        max_chars=5000,
    )

    assert bundle.summary == "User prefers dark mode and large fonts"
    assert len(bundle.items) == 1
    assert bundle.total_items == 1
    assert bundle.truncated is False
    client.close()


def test_memory_write_unauthenticated(mock_org_id, mock_project_id, httpx_mock: HTTPXMock):
    """Test write memory without authentication."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write",
        status_code=401,
        json={"error": "unauthorized", "message": "Authentication required"},
        method="POST",
    )

    client = Contiss(api_key="invalid_key")
    with pytest.raises(AuthenticationError):
        client.memory.write(
            org_id=mock_org_id, project_id=mock_project_id, content="Test"
        )
    client.close()


def test_memory_project_not_found(
    mock_api_key, mock_org_id, mock_project_id, httpx_mock: HTTPXMock
):
    """Test write memory to non-existent project."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write",
        status_code=404,
        json={"error": "not_found", "message": "Project not found"},
        method="POST",
    )

    client = Contiss(api_key=mock_api_key)
    with pytest.raises(NotFoundError):
        client.memory.write(
            org_id=mock_org_id, project_id="invalid_project", content="Test"
        )
    client.close()


def test_memory_validation_error(mock_api_key, mock_org_id, mock_project_id, httpx_mock: HTTPXMock):
    """Test validation error on memory write."""
    httpx_mock.add_response(
        url="https://api.contiss.ai/memory/write",
        status_code=400,
        json={"error": "validation_error", "message": "Content is required"},
        method="POST",
    )

    client = Contiss(api_key=mock_api_key)
    with pytest.raises(ValidationError):
        client.memory.write(org_id=mock_org_id, project_id=mock_project_id, content="")
    client.close()
