"""Tests for document store."""
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.documents import DocumentStore


@pytest.fixture
def db():
    database = SQLiteDatabase(":memory:")
    yield database
    database.close()


@pytest.fixture
def docs(db):
    return DocumentStore(db)


def test_create_document(docs):
    doc = docs.create(
        doc_type="session_log",
        title="Session 2026-03-01",
        content="# Session\nDid stuff.",
        project="greymatter",
        summary="Built solo mode core library.",
    )
    assert doc["id"].startswith("doc-")
    assert doc["doc_type"] == "session_log"
    assert doc["token_estimate"] > 0


def test_get_document(docs):
    created = docs.create(doc_type="design", title="Test", content="Content")
    fetched = docs.get(created["id"])
    assert fetched is not None
    assert fetched["title"] == "Test"


def test_search_by_type(docs):
    docs.create(doc_type="session_log", title="Session", content="Content")
    docs.create(doc_type="design", title="Design", content="Content")
    results = docs.search(doc_type="session_log")
    assert len(results) == 1
    assert results[0]["doc_type"] == "session_log"


def test_search_by_project(docs):
    docs.create(doc_type="session_log", title="A", content="A", project="arena")
    docs.create(doc_type="session_log", title="B", content="B", project="greymatter")
    results = docs.search(project="greymatter")
    assert len(results) == 1
    assert results[0]["title"] == "B"


def test_search_by_tags(docs):
    docs.create(doc_type="design", title="A", content="A", tags="architecture,database")
    docs.create(doc_type="design", title="B", content="B", tags="testing,tdd")
    results = docs.search(tags="database")
    assert len(results) == 1
    assert results[0]["title"] == "A"


def test_token_estimate_auto_calculated(docs):
    short_doc = docs.create(doc_type="design", title="Short", content="Hello")
    long_doc = docs.create(doc_type="design", title="Long", content="word " * 1000)
    assert long_doc["token_estimate"] > short_doc["token_estimate"]


def test_get_context_respects_max_tokens(docs):
    # Create a large doc (should get summary only) and small doc (full content)
    docs.create(
        doc_type="session_log", title="Big", content="word " * 2000,
        project="greymatter", summary="Big summary.",
    )
    docs.create(
        doc_type="session_log", title="Small", content="Short content.",
        project="greymatter", summary="Small summary.",
    )
    context = docs.get_context(project="greymatter", max_tokens=500)
    assert len(context) > 0
    # Should get at least summaries, not blow past token limit
    total_tokens = sum(c.get("token_estimate", 0) for c in context)
    assert total_tokens <= 600  # some leeway for overhead


def test_import_file(docs, tmp_path):
    md_file = tmp_path / "test-doc.md"
    md_file.write_text("# Test Document\n\nSome content here.")
    doc = docs.import_file(str(md_file), doc_type="research", project="arena")
    assert doc["title"] == "test-doc"
    assert "Some content here" in doc["content"]


def test_export_markdown(docs):
    doc = docs.create(
        doc_type="session_log", title="Session 2026-03-01",
        content="# Session Log\n\nDid stuff.", summary="Built things.",
    )
    md = docs.export_markdown(doc["id"])
    assert "Session 2026-03-01" in md
    assert "Did stuff." in md
