from __future__ import annotations

from pathlib import Path

import pytest

from project_brain.build.doc_parser import DocumentParser
from project_brain.build.document_content import DocumentContentPolicy
from project_brain.graph.json_store import JsonStore
from project_brain.query.engine import QueryEngine
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex
from project_brain.watcher.updater import IncrementalUpdater


class RecordingSemanticIndex:
    def __init__(self) -> None:
        self.added: list[str] = []
        self.removed: list[str] = []

    def add(self, node_id: str, content: str, is_test: bool = False) -> None:
        self.added.append(node_id)

    def remove(self, node_id: str) -> None:
        self.removed.append(node_id)

    def save(self, path: str) -> None:
        pass


@pytest.fixture
def document_setup(tmp_path: Path) -> dict:
    project = tmp_path / "project"
    (project / "docs").mkdir(parents=True)
    store = JsonStore(project / ".pb")
    keyword_index = KeywordIndex()
    symbol_index = SymbolIndex()
    file_index = FileIndex()
    semantic_index = RecordingSemanticIndex()
    updater = IncrementalUpdater(
        store,
        keyword_index,
        symbol_index,
        file_index,
        project,
        semantic_index,
    )
    return {
        "project": project,
        "store": store,
        "keyword": keyword_index,
        "file_index": file_index,
        "semantic": semantic_index,
        "updater": updater,
    }


def _write_doc(path: Path, title: str, concept: str) -> None:
    path.write_text(
        f"# {title}\n\n## Details\n\nThe `{concept}` component is documented here.\n",
        encoding="utf-8",
    )


def test_document_create_indexes_all_owned_nodes_with_posix_path(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    keyword = document_setup["keyword"]
    semantic = document_setup["semantic"]
    path = project / "docs" / "guide.md"
    _write_doc(path, "Guide", "OrderService")

    assert updater.update([r"docs\guide.md"]) == 1

    document = store.get_nodes_by_type("document")[0]
    sections = store.get_nodes_by_type("section")
    concepts = store.get_nodes_by_type("concept")
    all_ids = {document["id"], *(n["id"] for n in sections + concepts)}
    assert document["path"] == "docs/guide.md"
    assert all_ids <= set(keyword.documents)
    assert all_ids <= set(semantic.added)
    assert document_setup["file_index"].get("docs/guide.md")["kind"] == "document"


def test_document_modify_replaces_nodes_and_search_indexes(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    keyword = document_setup["keyword"]
    semantic = document_setup["semantic"]
    path = project / "docs" / "guide.md"
    _write_doc(path, "Old Guide", "OldService")
    assert updater.update(["docs/guide.md"]) == 1
    old_ids = {
        node["id"]
        for kind in ("document", "section", "concept")
        for node in store.get_nodes_by_type(kind)
    }
    old_concept_id = store.get_nodes_by_type("concept")[0]["id"]

    _write_doc(path, "New Guide", "NewService")
    assert updater.update(["docs/guide.md"]) == 1

    assert [d["title"] for d in store.get_nodes_by_type("document")] == ["New Guide"]
    assert [c["name"] for c in store.get_nodes_by_type("concept")] == ["NewService"]
    assert old_concept_id not in keyword.documents
    assert old_ids <= set(semantic.removed)
    current_ids = {
        node["id"]
        for kind in ("document", "section", "concept")
        for node in store.get_nodes_by_type(kind)
    }
    assert current_ids <= set(keyword.documents)


def test_document_delete_removes_graph_and_indexes(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    keyword = document_setup["keyword"]
    semantic = document_setup["semantic"]
    path = project / "docs" / "guide.md"
    _write_doc(path, "Guide", "OrderService")
    assert updater.update(["docs/guide.md"]) == 1
    old_ids = {
        node["id"]
        for kind in ("document", "section", "concept")
        for node in store.get_nodes_by_type(kind)
    }

    path.unlink()
    assert updater.update(["docs/guide.md"]) == 1

    assert not store.get_nodes_by_type("document")
    assert not store.get_nodes_by_type("section")
    assert not store.get_nodes_by_type("concept")
    assert old_ids.isdisjoint(keyword.documents)
    assert old_ids <= set(semantic.removed)
    assert document_setup["file_index"].get("docs/guide.md") is None


def test_document_rename_is_one_delete_and_upsert_batch(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    old_path = project / "docs" / "old.md"
    new_path = project / "docs" / "new.md"
    _write_doc(old_path, "Guide", "OrderService")
    assert updater.update(["docs/old.md"]) == 1
    old_id = store.get_nodes_by_type("document")[0]["id"]

    old_path.rename(new_path)
    assert updater.update(["docs/old.md", "docs/new.md"]) == 2

    documents = store.get_nodes_by_type("document")
    assert [document["path"] for document in documents] == ["docs/new.md"]
    assert documents[0]["id"] != old_id
    assert store.get_node(old_id) is None


def test_inward_symlink_document_keeps_lexical_owner(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    file_index = document_setup["file_index"]
    updater.document_content_policy = DocumentContentPolicy(
        include=("docs/alias.md",),
        max_file_bytes=4096,
        max_total_bytes=4096,
    )
    source = project / "document-source"
    alias = project / "docs" / "alias.md"
    _write_doc(source, "Linked Guide", "LinkedService")
    try:
        alias.symlink_to(source)
    except (NotImplementedError, OSError) as exc:
        pytest.skip(f"symlinks are unavailable on this platform: {exc}")

    assert updater.update(["docs/alias.md"]) == 1

    document = store.get_nodes_by_type("document")[0]
    assert document["path"] == "docs/alias.md"
    assert document["content_complete"] is True
    assert "LinkedService" in document["content"]
    info = file_index.get("docs/alias.md")
    assert info is not None
    assert info["file_id"] == document["id"]
    assert file_index.get("document-source") is None
    assert all(
        section["doc_id"] == document["id"]
        for section in store.get_nodes_by_type("section")
    )
    assert all(
        concept["source"] == document["id"]
        for concept in store.get_nodes_by_type("concept")
    )
    assert all(
        chunk["doc_id"] == document["id"]
        for chunk in store.get_nodes_by_type("document_chunk")
    )


def test_document_parse_failure_preserves_last_good_artifact(
    document_setup, monkeypatch,
):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    keyword = document_setup["keyword"]
    path = project / "docs" / "guide.md"
    _write_doc(path, "Good Guide", "GoodService")
    assert updater.update(["docs/guide.md"]) == 1
    old_nodes = {
        node["id"]: dict(node)
        for kind in ("document", "section", "concept")
        for node in store.get_nodes_by_type(kind)
    }
    old_keyword_documents = dict(keyword.documents)
    _write_doc(path, "Broken Replacement", "BrokenService")

    def fail_parse(*args, **kwargs):
        raise ValueError("synthetic document parse failure")

    monkeypatch.setattr(DocumentParser, "parse_file", fail_parse)

    assert updater.update(["docs/guide.md"]) == 0
    assert {node_id: store.get_node(node_id) for node_id in old_nodes} == old_nodes
    assert keyword.documents == old_keyword_documents


def test_legacy_document_without_file_index_can_be_deleted(document_setup):
    project = document_setup["project"]
    updater = document_setup["updater"]
    store = document_setup["store"]
    keyword = document_setup["keyword"]
    path = project / "docs" / "legacy.md"
    _write_doc(path, "Legacy", "LegacyService")
    result = DocumentParser().parse_file(path, project)
    for node in [result.document, *result.sections, *result.concepts]:
        data = node.to_dict()
        store.add_node(data)
        text = QueryEngine._index_text(data)
        if text:
            keyword.add(node.id, text)
    assert document_setup["file_index"].get("docs/legacy.md") is None

    path.unlink()
    assert updater.update(["docs/legacy.md"]) == 1
    assert not store.get_nodes_by_type("document")
    assert not store.get_nodes_by_type("section")
    assert not store.get_nodes_by_type("concept")


def test_same_concept_in_two_documents_has_document_scoped_ids(tmp_path: Path):
    project = tmp_path / "project"
    project.mkdir()
    first = project / "first.md"
    second = project / "second.md"
    _write_doc(first, "First", "SharedService")
    _write_doc(second, "Second", "SharedService")

    first_result = DocumentParser().parse_file(first, project)
    second_result = DocumentParser().parse_file(second, project)

    assert first_result.concepts[0].name == second_result.concepts[0].name
    assert first_result.concepts[0].id != second_result.concepts[0].id