from __future__ import annotations

import pytest

from project_brain.graph.json_store import JsonStore
from project_brain.graph.validation import GraphValidationError, validate_graph_state
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex


def _snapshot_graph(tmp_path, *, content_bytes: int = 3, char_end: int = 3):
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc",
        "type": "document",
        "title": "Guide",
        "path": "docs/guide.md",
        "format": "markdown",
        "line_count": 1,
        "md5": "digest",
        "content": "abc",
        "content_complete": True,
        "content_bytes": content_bytes,
        "content_state": "full",
    })
    store.add_node({
        "id": "section",
        "type": "section",
        "title": "Guide",
        "doc_id": "doc",
        "level": 1,
        "line_start": 1,
        "line_end": 1,
        "content": "",
    })
    store.add_node({
        "id": "chunk",
        "type": "document_chunk",
        "doc_id": "doc",
        "section_id": "section",
        "title": "Guide",
        "line_start": 1,
        "line_end": 1,
        "char_start": 0,
        "char_end": char_end,
    })
    files = FileIndex()
    files.add("docs/guide.md", {
        "file_id": "doc",
        "kind": "document",
        "nodes": ["section", "chunk"],
    })
    return store, files


def test_document_snapshot_integrity_validation_accepts_valid_ranges(tmp_path):
    store, files = _snapshot_graph(tmp_path)

    validate_graph_state(
        store, KeywordIndex(), SymbolIndex(), files,
    )


@pytest.mark.parametrize(
    ("content_bytes", "char_end", "message"),
    [
        (2, 3, "content_bytes"),
        (3, 99, "out-of-bounds"),
    ],
)
def test_document_snapshot_integrity_validation_rejects_corruption(
    tmp_path, content_bytes, char_end, message,
):
    store, files = _snapshot_graph(
        tmp_path, content_bytes=content_bytes, char_end=char_end,
    )

    with pytest.raises(GraphValidationError, match=message):
        validate_graph_state(store, KeywordIndex(), SymbolIndex(), files)


def test_validation_rejects_dangling_posting_without_retained_source(tmp_path):
    store, files = _snapshot_graph(tmp_path)
    keyword = KeywordIndex()
    keyword.add("missing_chunk", "needle", retain_source=False)
    # Simulate a corrupt v3 artifact whose source registry was lost while
    # posting/doc_len state survived.
    keyword.documents.pop("missing_chunk")

    with pytest.raises(GraphValidationError, match="missing_chunk"):
        validate_graph_state(store, keyword, SymbolIndex(), files)


def test_validation_rejects_inconsistent_document_content_state(tmp_path):
    store, files = _snapshot_graph(tmp_path)
    document = store.get_node("doc")
    store.add_node(dict(
        document,
        content=None,
        content_complete=False,
        content_bytes=3,
        content_state="full",
    ))

    with pytest.raises(GraphValidationError, match="incomplete"):
        validate_graph_state(store, KeywordIndex(), SymbolIndex(), files)