from __future__ import annotations

from pathlib import Path
from types import SimpleNamespace

import pytest

from project_brain.__main__ import _cmd_build
from project_brain.build.builder import GraphBuildError, GraphBuilder
from project_brain.build.document_content import (
    DocumentContentLimitError,
    DocumentContentPolicy,
)
from project_brain.config import Config
from project_brain.graph.generation import GenerationRepository
from project_brain.graph.json_store import JsonStore
from project_brain.graph.sqlite_store import SqliteStore
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex
from project_brain.watcher.reconciler import compute_graph_config_digest
from project_brain.watcher.updater import IncrementalUpdater


def _graph(project: Path, config: Config):
    store = JsonStore(project / ".botbrain" / "graph")
    keyword = KeywordIndex()
    files = FileIndex()
    builder = GraphBuilder(
        project, config, store, keyword, SymbolIndex(), files,
    )
    return builder, store, keyword, files


def _config(*, total: int, on_limit: str = "error") -> Config:
    config = Config.default()
    config.document_content_include = ["docs/**/*.md"]
    config.document_content_max_file_bytes = 1024
    config.document_content_max_total_bytes = total
    config.document_content_on_limit = on_limit
    return config


def _write(path: Path, marker: str, repeat: int = 1) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        f"# {marker}\n\n## Details\n\n" + (f"{marker} body text. " * repeat),
        encoding="utf-8",
    )


def test_full_build_stores_chunks_and_avoids_section_duplicate_index(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    path = project / "docs" / "guide.md"
    _write(path, "deep-marker", repeat=20)
    builder, store, keyword, files = _graph(project, _config(total=4096))

    stats = builder.build_all(persist=False)

    document = store.get_nodes_by_type("document")[0]
    chunks = store.get_nodes_by_type("document_chunk")
    sections = store.get_nodes_by_type("section")
    assert document["content_complete"] is True
    assert stats["stored_documents"] == 1
    assert stats["stored_document_bytes"] == document["content_bytes"]
    assert chunks
    assert all(chunk["id"] in keyword.doc_len for chunk in chunks)
    assert all(keyword.documents[chunk["id"]] == "" for chunk in chunks)
    assert all(section["id"] not in keyword.documents for section in sections)
    owned = set(files.get("docs/guide.md")["nodes"])
    assert {chunk["id"] for chunk in chunks} <= owned


def test_full_build_inward_symlink_snapshot_uses_lexical_owner(tmp_path):
    project = tmp_path / "project"
    docs = project / "docs"
    docs.mkdir(parents=True)
    source = project / "document-source"
    _write(source, "linked-marker", repeat=2)
    alias = docs / "alias.md"
    try:
        alias.symlink_to(source)
    except (NotImplementedError, OSError) as exc:
        pytest.skip(f"symlinks are unavailable on this platform: {exc}")
    config = _config(total=4096)
    config.document_content_include = ["docs/alias.md"]
    builder, store, _, files = _graph(project, config)

    stats = builder.build_all(persist=False)

    documents = store.get_nodes_by_type("document")
    assert [document["path"] for document in documents] == ["docs/alias.md"]
    assert documents[0]["content_complete"] is True
    assert "linked-marker" in documents[0]["content"]
    assert stats["stored_documents"] == 1
    assert files.get("docs/alias.md")["file_id"] == documents[0]["id"]
    assert files.get("document-source") is None


def test_full_build_total_error_never_persists_partial_state(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    _write(project / "docs" / "guide.md", "oversize", repeat=10)
    builder, _, _, _ = _graph(project, _config(total=16))

    with pytest.raises(GraphBuildError, match="max_total_bytes"):
        builder.build_all(persist=True)

    graph = project / ".botbrain" / "graph"
    assert not (graph / "nodes.json").exists()
    assert not (graph / "keyword_index.json").exists()


def test_full_build_total_omit_is_deterministic_and_metadata_only(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    first = project / "docs" / "a.md"
    second = project / "docs" / "b.md"
    _write(first, "first", repeat=2)
    _write(second, "second", repeat=2)
    first_size = len(first.read_text(encoding="utf-8").encode("utf-8"))
    config = _config(total=first_size, on_limit="omit")
    builder, store, keyword, _ = _graph(project, config)

    stats = builder.build_all(persist=False)

    documents = {
        document["path"]: document
        for document in store.get_nodes_by_type("document")
    }
    assert documents["docs/a.md"]["content_complete"] is True
    assert documents["docs/b.md"]["content_complete"] is False
    assert documents["docs/b.md"]["content_state"] == "omitted_oversize"
    assert stats["stored_documents"] == 1
    assert stats["stored_document_bytes"] == first_size
    assert all(
        chunk["doc_id"] == documents["docs/a.md"]["id"]
        for chunk in store.get_nodes_by_type("document_chunk")
    )
    omitted_section_ids = {
        section["id"]
        for section in store.get_nodes_by_type("section")
        if section["doc_id"] == documents["docs/b.md"]["id"]
    }
    assert omitted_section_ids <= set(keyword.doc_len)


def test_incremental_total_error_rolls_back_entire_batch(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    first = project / "docs" / "first.md"
    second = project / "docs" / "second.md"
    _write(first, "first", repeat=2)
    first_size = len(first.read_text(encoding="utf-8").encode("utf-8"))
    policy = DocumentContentPolicy(
        include=("docs/**/*.md",),
        max_file_bytes=1024,
        max_total_bytes=first_size + 5,
        on_limit="error",
    )
    store = JsonStore(project / ".pb")
    keyword = KeywordIndex()
    files = FileIndex()
    updater = IncrementalUpdater(
        store, keyword, SymbolIndex(), files, project,
        document_content_policy=policy,
    )
    assert updater.update(["docs/first.md"]) == 1
    before_nodes = {node["id"]: dict(node) for node in store.get_all_nodes()}
    before_keyword = keyword.snapshot()
    _write(second, "second", repeat=2)

    with pytest.raises(DocumentContentLimitError, match="max_total_bytes"):
        updater.update(["docs/second.md"])

    assert {node["id"]: node for node in store.get_all_nodes()} == before_nodes
    assert keyword.snapshot() == before_keyword
    assert files.get("docs/second.md") is None


def test_incremental_updates_input_digest_when_canonical_text_is_unchanged(
    tmp_path,
):
    project = tmp_path / "project"
    path = project / "docs" / "guide.md"
    path.parent.mkdir(parents=True)
    path.write_bytes(b"# Guide\r\n\r\nbody\r\n")
    policy = DocumentContentPolicy(
        include=("docs/**/*.md",),
        max_file_bytes=1024,
        max_total_bytes=4096,
        on_limit="error",
    )
    store = JsonStore(project / ".pb")
    updater = IncrementalUpdater(
        store, KeywordIndex(), SymbolIndex(), FileIndex(), project,
        document_content_policy=policy,
    )
    assert updater.update(["docs/guide.md"]) == 1
    before = store.get_nodes_by_type("document")[0]

    path.write_bytes(b"# Guide\n\nbody\n")
    assert updater.update(["docs/guide.md"]) == 1
    after = store.get_nodes_by_type("document")[0]

    assert after["md5"] == before["md5"]
    assert after["input_md5"] != before["input_md5"]


def test_incremental_omit_rebalances_like_full_build_and_promotes_on_delete(
    tmp_path,
):
    project = tmp_path / "project"
    project.mkdir()
    later = project / "docs" / "b.md"
    _write(later, "b", repeat=2)
    content_size = len(later.read_text(encoding="utf-8").encode("utf-8"))
    policy = DocumentContentPolicy(
        include=("docs/**/*.md",),
        max_file_bytes=1024,
        max_total_bytes=content_size,
        on_limit="omit",
    )
    store = JsonStore(project / ".pb")
    keyword = KeywordIndex()
    files = FileIndex()
    updater = IncrementalUpdater(
        store, keyword, SymbolIndex(), files, project,
        document_content_policy=policy,
    )

    assert updater.update(["docs/b.md"]) == 1
    assert store.get_nodes_by_type("document")[0]["content_complete"] is True

    earlier = project / "docs" / "a.md"
    _write(earlier, "a", repeat=2)
    # Adding an earlier path is one logical update: install a.md and demote
    # the already published b.md snapshot in the same commit.
    assert updater.update(["docs/a.md"]) == 2
    incremental = {
        document["path"]: bool(document["content_complete"])
        for document in store.get_nodes_by_type("document")
    }
    assert incremental == {"docs/a.md": True, "docs/b.md": False}

    config = _config(total=content_size, on_limit="omit")
    builder, rebuilt_store, rebuilt_keyword, _ = _graph(project, config)
    builder.build_all(persist=False)
    rebuilt = {
        document["path"]: bool(document["content_complete"])
        for document in rebuilt_store.get_nodes_by_type("document")
    }
    assert incremental == rebuilt
    assert set(keyword.doc_len) == set(rebuilt_keyword.doc_len)

    earlier.unlink()
    # Removing a.md releases the budget and promotes b.md immediately; no
    # separate event for the unchanged previously omitted file is required.
    assert updater.update(["docs/a.md"]) == 2
    remaining = store.get_nodes_by_type("document")
    assert [(doc["path"], doc["content_complete"]) for doc in remaining] == [
        ("docs/b.md", True),
    ]
    assert store.get_nodes_by_type("document_chunk")

    rebuilt_after_delete, rebuilt_store, _, _ = _graph(project, config)
    rebuilt_after_delete.build_all(persist=False)
    assert {
        document["path"]: bool(document["content_complete"])
        for document in rebuilt_store.get_nodes_by_type("document")
    } == {"docs/b.md": True}


def test_incremental_omit_reallocation_rolls_back_as_one_batch(
    tmp_path, monkeypatch,
):
    project = tmp_path / "project"
    project.mkdir()
    later = project / "docs" / "b.md"
    _write(later, "b", repeat=2)
    content_size = len(later.read_text(encoding="utf-8").encode("utf-8"))
    policy = DocumentContentPolicy(
        include=("docs/**/*.md",),
        max_file_bytes=1024,
        max_total_bytes=content_size,
        on_limit="omit",
    )
    store = JsonStore(project / ".pb")
    keyword = KeywordIndex()
    files = FileIndex()
    updater = IncrementalUpdater(
        store, keyword, SymbolIndex(), files, project,
        document_content_policy=policy,
    )
    assert updater.update(["docs/b.md"]) == 1

    before_nodes = {node["id"]: dict(node) for node in store.get_all_nodes()}
    before_keyword = keyword.snapshot()
    before_files = files.snapshot()
    _write(project / "docs" / "a.md", "a", repeat=2)

    def fail_persist():
        raise RuntimeError("simulated publish failure")

    monkeypatch.setattr(updater, "_persist", fail_persist)
    with pytest.raises(RuntimeError, match="simulated publish failure"):
        updater.update(["docs/a.md"])

    assert {node["id"]: node for node in store.get_all_nodes()} == before_nodes
    assert keyword.snapshot() == before_keyword
    assert files.snapshot() == before_files


def test_incremental_omit_uses_the_full_build_traversal_order(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    root_document = project / "z.md"
    _write(root_document, "z", repeat=2)
    content_size = len(
        root_document.read_text(encoding="utf-8").encode("utf-8")
    )
    policy = DocumentContentPolicy(
        include=("**/*.md",),
        max_file_bytes=1024,
        max_total_bytes=content_size,
        on_limit="omit",
    )
    store = JsonStore(project / ".pb")
    updater = IncrementalUpdater(
        store, KeywordIndex(), SymbolIndex(), FileIndex(), project,
        document_content_policy=policy,
    )
    assert updater.update(["z.md"]) == 1

    nested_document = project / "docs" / "a.md"
    _write(nested_document, "a", repeat=2)
    assert updater.update(["docs/a.md"]) == 1
    incremental = {
        document["path"]: bool(document["content_complete"])
        for document in store.get_nodes_by_type("document")
    }

    config = Config.default()
    config.document_content_include = ["**/*.md"]
    config.document_content_max_file_bytes = 1024
    config.document_content_max_total_bytes = content_size
    config.document_content_on_limit = "omit"
    builder, rebuilt_store, _, _ = _graph(project, config)
    builder.build_all(persist=False)
    assert incremental == {
        document["path"]: bool(document["content_complete"])
        for document in rebuilt_store.get_nodes_by_type("document")
    }
    assert incremental == {"z.md": True, "docs/a.md": False}


def test_document_content_config_changes_graph_digest():
    first = Config.default()
    second = Config.default()
    second.document_content_include = ["docs/**/*.md"]

    assert compute_graph_config_digest(first) != compute_graph_config_digest(second)


def test_build_cli_persists_repeatable_document_patterns(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    _write(project / "docs" / "guide.md", "guide")
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=["README.md", "docs/**/*.md", "README.md"],
    )

    _cmd_build(project, args)

    config = Config.load(str(project))
    assert config.document_content_include == ["README.md", "docs/**/*.md"]
    metadata = GenerationRepository(
        project / ".botbrain" / "graph"
    ).current_manifest()["metadata"]
    assert metadata["stored_documents"] == 1
    assert metadata["stored_document_bytes"] > 0


def test_sqlite_total_error_keeps_last_published_graph(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    first = project / "docs" / "first.md"
    _write(first, "first", repeat=2)
    first_size = len(first.read_text(encoding="utf-8").encode("utf-8"))
    config = _config(total=first_size)
    config.storage_backend = "sqlite"
    config.save(str(project))
    _cmd_build(project)

    _write(project / "docs" / "second.md", "second", repeat=2)
    with pytest.raises(GraphBuildError, match="max_total_bytes"):
        _cmd_build(project)

    store = SqliteStore(project / ".botbrain" / "graph")
    try:
        documents = store.get_nodes_by_type("document")
        assert [document["path"] for document in documents] == [
            "docs/first.md"
        ]
        assert documents[0]["content_complete"] is True
    finally:
        store.close()