import pytest
from types import SimpleNamespace
from project_brain.graph.json_store import JsonStore
from project_brain.query.index import KeywordIndex, SymbolIndex, FileIndex
from project_brain.query.engine import QueryEngine, _decode_content_cursor
from project_brain.graph.models import Edge


@pytest.fixture
def engine(tmp_dir):
    store = JsonStore(tmp_dir)
    kw_idx = KeywordIndex()
    sym_idx = SymbolIndex()
    file_idx = FileIndex()

    store.add_node({"id": "fn_1", "type": "function", "name": "create_order", "signature": "def create_order()", "path": "src/order.py", "line_start": 10, "line_end": 20, "module_id": "mod_1", "visibility": "public"})
    store.add_node({"id": "fn_2", "type": "function", "name": "validate_order", "signature": "def validate_order()", "path": "src/order.py", "line_start": 25, "line_end": 35, "module_id": "mod_1", "visibility": "public"})
    store.add_node({"id": "fn_3", "type": "function", "name": "process_payment", "signature": "def process_payment()", "path": "src/payment.py", "line_start": 10, "line_end": 20, "module_id": "mod_2", "visibility": "public"})
    store.add_node({"id": "cls_1", "type": "class", "name": "OrderService", "kind": "class", "path": "src/order.py", "line_start": 1, "line_end": 50, "module_id": "mod_1"})
    store.add_node({"id": "mod_1", "type": "module", "name": "order", "path": "src/order"})
    store.add_node({"id": "mod_2", "type": "module", "name": "payment", "path": "src/payment"})
    store.add_node({"id": "test_1", "type": "test", "name": "test_create_order", "path": "tests/test_order.py", "line_start": 5, "framework": "pytest"})
    store.add_node({"id": "doc_1", "type": "document", "title": "Order Design", "path": "docs/order.md"})
    store.add_node({"id": "conv_1", "type": "convention", "category": "naming", "name": "Function Naming", "description": "Use snake_case", "source": "code_analysis", "scope": None})

    store.add_edge(Edge(id="e1", type="CALL", source="fn_1", target="fn_2"))
    store.add_edge(Edge(id="e2", type="CALL", source="fn_1", target="fn_3"))
    store.add_edge(Edge(id="e3", type="CONTAIN", source="mod_1", target="fn_1"))
    store.add_edge(Edge(id="e4", type="CONTAIN", source="mod_1", target="fn_2"))
    store.add_edge(Edge(id="e5", type="CONTAIN", source="mod_1", target="cls_1"))
    store.add_edge(Edge(id="e6", type="TEST", source="test_1", target="fn_1"))
    store.add_edge(Edge(id="e7", type="DESCRIBE", source="doc_1", target="cls_1", properties={"method": "explicit"}))
    store.add_edge(Edge(id="e8", type="DEPEND", source="mod_1", target="mod_2"))

    sym_idx.add("create_order", "fn_1")
    sym_idx.add("validate_order", "fn_2")
    sym_idx.add("process_payment", "fn_3")
    sym_idx.add("OrderService", "cls_1")
    sym_idx.add("order", "mod_1")
    sym_idx.add("payment", "mod_2")

    kw_idx.add("fn_1", "create_order def create_order()")
    kw_idx.add("fn_2", "validate_order def validate_order()")
    kw_idx.add("cls_1", "OrderService class")

    file_idx.add("src/order.py", {"file_id": "file_1", "language": "python", "nodes": ["fn_1", "fn_2", "cls_1"]})

    return QueryEngine(store, kw_idx, sym_idx, file_idx)


def test_keyword_search(engine):
    results = engine.keyword_search("create_order")
    assert len(results) >= 1
    assert any(r["name"] == "create_order" for r in results)


def test_query_boundaries_and_direct_id_type_filter(engine):
    assert engine.keyword_search("create_order", top_k=0) == []
    assert engine.keyword_search("create_order", top_k=-1) == []
    assert engine.keyword_search(None) == []
    assert engine.keyword_search(
        "x" * (engine.MAX_SEARCH_QUERY_CHARS + 1)
    ) == []
    assert engine.keyword_search(
        "create_order", scope="x" * (engine.MAX_SEARCH_SCOPE_CHARS + 1)
    ) == []
    assert engine.keyword_search("create_order", top_k="invalid") == []
    assert engine.keyword_search("create_order", test_filter="invalid") == []
    assert engine.get_callers("fn_2", depth=0) == []
    assert engine.get_callees("fn_1", depth=-1) == []
    assert engine.get_history("src/order.py", limit=-1) == []
    assert engine._resolve_id("cls_1", expected_type="function") is None
    assert engine._resolve_ids("cls_1", expected_type="function") == []


def test_locate_symbol(engine):
    results = engine.locate_symbol("create_order")
    assert len(results) == 1
    assert results[0]["id"] == "fn_1"
    assert results[0]["name"] == "create_order"


def test_locate_symbol_with_kind(engine):
    results = engine.locate_symbol("OrderService", kind="class")
    assert len(results) == 1
    assert results[0]["kind"] == "class"


def test_generic_language_symbol_is_locatable_with_exact_evidence(tmp_path):
    store = JsonStore(tmp_path / "graph")
    keyword = KeywordIndex()
    symbols = SymbolIndex()
    files = FileIndex()
    store.add_node({
        "id": "sym_limit",
        "type": "symbol",
        "name": "RUST_LIMIT",
        "kind": "constant",
        "file_id": "file_rust",
        "line_start": 3,
        "line_end": 3,
        "byte_start": 20,
        "byte_end": 51,
        "visibility": "public",
        "is_definition": True,
        "data_type": "usize",
        "value": "8",
        "owner_name": None,
    })
    store.add_node({
        "id": "file_rust",
        "type": "file",
        "name": "model.rs",
        "path": "src/model.rs",
        "language": "rust",
    })
    symbols.add("RUST_LIMIT", "sym_limit")
    query = QueryEngine(store, keyword, symbols, files)

    located = query.locate_symbol("RUST_LIMIT", kind="constant")
    assert len(located) == 1
    assert located[0]["type"] == "symbol"
    assert located[0]["file"] == "src/model.rs"
    assert located[0]["byte_start"] == 20
    assert located[0]["data_type"] == "usize"
    assert located[0]["value"] == "8"
    assert query.get_symbol_info("sym_limit")["data_type"] == "usize"


def test_get_symbol_info(engine):
    info = engine.get_symbol_info("fn_1")
    assert info is not None
    assert info["name"] == "create_order"
    assert len(info["callees"]) == 2
    assert len(info["tests"]) == 1


def test_get_symbol_info_exposes_p2_relation_edges(engine):
    engine.store.add_node({"id": "cls_user", "type": "class", "name": "User"})
    engine.store.add_node({"id": "field_name", "type": "symbol", "name": "name"})
    engine.store.add_node({"id": "trace_macro", "type": "symbol", "name": "TRACE"})
    evidence = [{"kind": "call", "name": "TRACE", "line_start": 3}]
    engine.store.update_node("fn_1", {"references": evidence})
    engine.store.add_edge(Edge(
        id="fn_1->cls_user:TYPE_REF", type="TYPE_REF",
        source="fn_1", target="cls_user",
    ))
    engine.store.add_edge(Edge(
        id="fn_1->field_name:ACCESS", type="ACCESS",
        source="fn_1", target="field_name", properties={"mode": "write"},
    ))
    engine.store.add_edge(Edge(
        id="fn_1->trace_macro:REFERENCE", type="REFERENCE",
        source="fn_1", target="trace_macro",
    ))

    info = engine.get_symbol_info("fn_1", include="referenced_types/accesses")
    user = engine.get_symbol_info("cls_user", include="type_references")

    assert info["referenced_types"] == [{"id": "cls_user", "name": "User"}]
    assert info["accesses"] == [{"id": "field_name", "name": "name"}]
    assert user["type_references"] == [{"id": "fn_1", "name": "create_order"}]
    any_info = engine.get_symbol_info("fn_1")
    assert any_info["references"] == evidence
    assert any_info["symbol_references"] == [{"id": "trace_macro", "name": "TRACE"}]


def test_get_symbol_info_exposes_p31_relations(engine):
    for node in (
        {"id": "derived", "type": "function", "name": "Derived::run"},
        {"id": "template", "type": "function", "name": "identity"},
        {"id": "macro", "type": "symbol", "name": "TRACE"},
    ):
        engine.store.add_node(node)
    engine.store.add_edge(Edge(
        id="fn_1->derived:OVERRIDES", type="OVERRIDES",
        source="fn_1", target="derived",
    ))
    engine.store.add_edge(Edge(
        id="template->fn_1:TEMPLATE_SPECIALIZATION",
        type="TEMPLATE_SPECIALIZATION", source="template", target="fn_1",
    ))
    engine.store.add_edge(Edge(
        id="fn_1->macro:MACRO_CALLS", type="MACRO_CALLS",
        source="fn_1", target="macro",
    ))

    info = engine.get_symbol_info(
        "fn_1", include="overridden_by/template_sources/called_macros",
    )

    assert info["overridden_by"] == [{"id": "derived", "name": "Derived::run"}]
    assert info["template_sources"] == [{"id": "template", "name": "identity"}]
    assert info["called_macros"] == [{"id": "macro", "name": "TRACE"}]


def test_locate_symbol_supports_module_and_owner_qualified_names(engine):
    for node in (
        {
            "id": "sync_body", "type": "class", "name": "Body",
            "module_path": "sync_impl",
        },
        {
            "id": "async_body", "type": "class", "name": "Body",
            "module_path": "async_impl",
        },
        {
            "id": "sync_poll", "type": "function", "name": "poll",
            "module_path": "sync_impl", "class_name": "Body",
        },
    ):
        engine.store.add_node(node)
        engine.symbol_index.add(node["name"], node["id"])

    assert [item["id"] for item in engine.locate_symbol("sync_impl::Body")] == [
        "sync_body"
    ]
    assert [
        item["id"] for item in engine.locate_symbol("sync_impl::Body::poll")
    ] == ["sync_poll"]


def test_call_graph_traverses_explicit_ffi_bridge(engine):
    engine.store.add_node({
        "id": "fn_rust_ffi_decl", "type": "function", "name": "native_save",
    })
    engine.store.add_node({
        "id": "fn_c_native_save", "type": "function", "name": "native_save",
    })
    engine.store.add_edge(Edge(
        id="fn_1->fn_rust_ffi_decl:CALL", type="CALL",
        source="fn_1", target="fn_rust_ffi_decl",
    ))
    engine.store.add_edge(Edge(
        id="fn_rust_ffi_decl->fn_c_native_save:FFI_BIND", type="FFI_BIND",
        source="fn_rust_ffi_decl", target="fn_c_native_save",
    ))

    callees = engine.get_callees("fn_1", depth=2)
    callers = engine.get_callers("fn_c_native_save", depth=2)

    callee_ids = [item["id"] for item in callees]
    caller_ids = [item["id"] for item in callers]
    assert callee_ids.index("fn_rust_ffi_decl") < callee_ids.index("fn_c_native_save")
    assert caller_ids == ["fn_rust_ffi_decl", "fn_1"]
    info = engine.get_symbol_info("fn_rust_ffi_decl", include="ffi_bindings")
    assert info["ffi_bindings"] == [{"id": "fn_c_native_save", "name": "native_save"}]


def test_get_symbol_info_rejects_document_content_bypass(engine):
    marker = "full-snapshot-marker" * 10_000
    engine.store.add_node({
        "id": "doc_private",
        "type": "document",
        "title": "Private guide",
        "path": "docs/private.md",
        "content": marker,
        "content_complete": True,
    })

    assert engine.get_symbol_info("doc_private") is None


def test_get_symbol_info_omits_indexed_function_body(engine):
    marker = "function-body-marker" * 10_000
    engine.store.update_node("fn_1", {"body": marker})

    info = engine.get_symbol_info("fn_1")

    assert info is not None
    assert info["name"] == "create_order"
    assert "body" not in info
    assert marker not in str(info)


def test_get_callers(engine):
    callers = engine.get_callers("fn_2")
    assert len(callers) >= 1
    assert any(c["name"] == "create_order" for c in callers)


def test_get_callees(engine):
    callees = engine.get_callees("fn_1")
    assert len(callees) == 2
    names = [c["name"] for c in callees]
    assert "validate_order" in names
    assert "process_payment" in names


def test_get_dependencies(engine):
    deps = engine.get_dependencies("mod_1", direction="down")
    assert len(deps["downstream"]) == 1
    assert deps["downstream"][0]["name"] == "payment"


def test_get_dependencies_combines_legacy_edges_and_deep_descendants(engine):
    for node in (
        {"id": "mod_child", "type": "module", "name": "child"},
        {"id": "mod_grand", "type": "module", "name": "grand"},
        {"id": "mod_external", "type": "module", "name": "external"},
        {"id": "mod_deep_dep", "type": "module", "name": "deep_dep"},
        {"id": "file_deep", "type": "file", "path": "src/order/a/b.py"},
        {"id": "file_external", "type": "file", "path": "src/external.py"},
    ):
        engine.store.add_node(node)
    for edge in (
        Edge(id="deep_1", type="CONTAIN", source="mod_1", target="mod_child"),
        Edge(id="deep_2", type="CONTAIN", source="mod_child", target="mod_grand"),
        Edge(id="deep_3", type="CONTAIN", source="mod_grand", target="file_deep"),
        Edge(id="deep_4", type="CONTAIN", source="mod_external", target="file_external"),
        Edge(id="deep_5", type="DEPEND", source="file_deep", target="mod_deep_dep"),
        Edge(id="deep_6", type="DEPEND", source="file_external", target="mod_grand"),
    ):
        engine.store.add_edge(edge)

    deps = engine.get_dependencies("mod_1", direction="both")

    assert {item["id"] for item in deps["downstream"]} == {"mod_2", "mod_deep_dep"}
    assert {item["id"] for item in deps["upstream"]} == {"mod_external"}


def test_get_module_contents(engine):
    contents = engine.get_module_contents("mod_1")
    assert contents is not None
    assert contents["module"]["name"] == "order"
    assert len(contents["functions"]) >= 2
    assert len(contents["classes"]) == 1


def test_get_file_symbols(engine):
    symbols = engine.get_file_symbols("src/order.py")
    assert len(symbols) == 3
    names = [s["name"] for s in symbols]
    assert "create_order" in names
    assert "OrderService" in names


def test_get_related_tests(engine):
    tests = engine.get_related_tests("fn_1")
    assert len(tests) == 1
    assert tests[0]["name"] == "test_create_order"


def test_get_conventions(engine):
    conventions = engine.get_conventions()
    assert len(conventions) >= 1
    assert conventions[0]["category"] == "naming"


def test_get_conventions_scope_filters_exactly(engine):
    engine.store.add_node({
        "id": "conv_scoped",
        "type": "convention",
        "category": "architecture",
        "name": "Order boundary",
        "description": "Keep payment outside order",
        "source": "code_analysis",
        "scope": "mod_1",
    })

    assert len(engine.get_conventions()) == 2
    scoped = engine.get_conventions("mod_1")
    assert [item["name"] for item in scoped] == ["Order boundary"]
    assert engine.get_conventions("mod_missing") == []


def test_get_doc_links(engine):
    docs = engine.get_doc_links("cls_1")
    assert len(docs) == 1
    assert docs[0]["title"] == "Order Design"


def test_resolve_id_by_name(engine):
    resolved = engine._resolve_id("create_order")
    assert resolved == "fn_1"


def test_resolve_id_by_id(engine):
    resolved = engine._resolve_id("fn_1")
    assert resolved == "fn_1"


def test_resolve_id_not_found(engine):
    resolved = engine._resolve_id("nonexistent")
    assert resolved is None


def test_keyword_search_returns_file_path(engine):
    engine.store.add_node({"id": "file_x", "type": "file", "path": "src/x.py", "language": "python"})
    engine.store.add_node({"id": "fn_x", "type": "function", "name": "do_x", "file_id": "file_x", "line_start": 5, "is_test": False})
    engine.keyword_index.add("fn_x", "do_x something")
    results = engine.keyword_search("do_x")
    assert results
    hit = [r for r in results if r["id"] == "fn_x"][0]
    assert hit["file"] == "src/x.py"


def test_keyword_search_test_filter(engine):
    engine.store.add_node({"id": "fn_t", "type": "function", "name": "test_foo", "is_test": True, "path": "tests/t.py", "line_start": 1})
    engine.store.add_node({"id": "fn_n", "type": "function", "name": "foo_bar", "is_test": False, "path": "src/f.py", "line_start": 1})
    engine.keyword_index.add("fn_t", "test_foo")
    engine.keyword_index.add("fn_n", "foo_bar")
    # normal (default): excludes test functions
    normal_results = engine.keyword_search("test_foo", test_filter="normal")
    assert not any(r["id"] == "fn_t" for r in normal_results)
    # test: only test functions
    test_results = engine.keyword_search("test_foo", test_filter="test")
    assert any(r["id"] == "fn_t" for r in test_results)
    assert not any(r["id"] == "fn_n" for r in test_results)
    # all: everything
    all_results = engine.keyword_search("test_foo", test_filter="all")
    assert any(r["id"] == "fn_t" for r in all_results)


def test_locate_symbol_case_insensitive(engine):
    results = engine.locate_symbol("orderservice")
    assert any(r["id"] == "cls_1" for r in results)


def test_get_symbol_info_ambiguous(engine):
    engine.store.add_node({"id": "cls_2", "type": "class", "name": "OrderService", "kind": "class", "path": "other.py", "line_start": 1})
    engine.symbol_index.add("OrderService", "cls_2")
    info = engine.get_symbol_info("OrderService")
    assert info is not None
    assert info.get("ambiguous") is True
    assert len(info["candidates"]) == 2


def test_get_module_contents_dedup(engine):
    engine.store.add_edge(Edge(id="e3_dup", type="CONTAIN", source="mod_1", target="fn_1"))
    contents = engine.get_module_contents("mod_1")
    fn_ids = [f["id"] for f in contents["functions"]]
    assert fn_ids.count("fn_1") == 1


def test_get_module_api_filters_exported(engine):
    engine.store.update_node("fn_1", {"is_exported": False})
    engine.store.update_node("fn_2", {"is_exported": True})
    result = engine.get_module_api("mod_1")
    assert result is not None
    fn_ids = [f["id"] for f in result["functions"]]
    assert "fn_1" not in fn_ids
    assert "fn_2" in fn_ids
    assert any(c["id"] == "cls_1" for c in result["classes"])


def test_get_class_methods_fallback(engine):
    engine.store.add_node({"id": "cls_y", "type": "class", "name": "Bar", "kind": "struct", "path": "b.rs", "line_start": 1})
    engine.store.add_node({"id": "fn_b1", "type": "function", "name": "b1", "class_id": "cls_y", "class_name": "Bar", "line_start": 2, "is_test": False})
    engine.store.add_node({"id": "fn_b2", "type": "function", "name": "b2", "class_id": "cls_y", "class_name": "Bar", "line_start": 5, "is_test": False})
    engine.symbol_index.add("Bar", "cls_y")
    methods = engine.get_class_methods("cls_y")
    assert set(methods) == {"fn_b1", "fn_b2"}


def test_impact_analysis_for_struct(engine):
    engine.store.add_node({"id": "cls_x", "type": "class", "name": "Mutex", "kind": "struct", "methods": ["fn_m1", "fn_m2"], "path": "src/m.rs", "line_start": 1})
    engine.store.add_node({"id": "fn_m1", "type": "function", "name": "lock", "file_id": "file_x", "class_id": "cls_x", "class_name": "Mutex", "module_id": "mod_1", "line_start": 5, "is_test": False})
    engine.store.add_node({"id": "fn_m2", "type": "function", "name": "unlock", "file_id": "file_x", "class_id": "cls_x", "class_name": "Mutex", "module_id": "mod_1", "line_start": 10, "is_test": False})
    engine.store.add_node({"id": "fn_caller", "type": "function", "name": "do_work", "file_id": "file_y", "module_id": "mod_1", "line_start": 1, "is_test": False})
    engine.store.add_edge(Edge(id="ec1", type="CALL", source="fn_caller", target="fn_m1"))
    engine.symbol_index.add("Mutex", "cls_x")
    engine.symbol_index.add("lock", "fn_m1")

    result = engine.impact_analysis("cls_x")
    assert result["target"] == "cls_x"
    caller_ids = [c["id"] for c in result["affected_functions"]]
    assert "fn_caller" in caller_ids
    assert result["risk_level"] == "medium"


def test_impact_analysis_unknown_target_is_explicit(engine):
    result = engine.impact_analysis("fn_missing")
    assert result == {
        "target": "fn_missing",
        "error": "Target not found: fn_missing",
        "found": False,
    }


def test_get_code_slice_supports_file_path_kind_and_source_flag(tmp_path, monkeypatch):
    project = tmp_path / "project"
    source_dir = project / "src"
    source_dir.mkdir(parents=True)
    source_path = source_dir / "sample.py"
    source_path.write_text("one\ntwo\nthree\nfour\n", encoding="utf-8")

    store = JsonStore(tmp_path / "graph")
    keyword = KeywordIndex()
    symbols = SymbolIndex()
    files = FileIndex()
    store.add_node({
        "id": "file_sample",
        "type": "file",
        "path": "src/sample.py",
        "line_count": 4,
    })
    store.add_node({
        "id": "fn_sample",
        "type": "function",
        "name": "sample",
        "file_id": "file_sample",
        "line_start": 2,
        "line_end": 3,
    })
    symbols.add("sample", "fn_sample")
    files.add("src/sample.py", {
        "file_id": "file_sample",
        "language": "python",
        "nodes": ["fn_sample"],
    })
    query = QueryEngine(
        store, keyword, symbols, files, project_path=str(project)
    )

    file_result = query.get_code_slice("src/sample.py", kind="file")
    assert file_result["source"] == "one\ntwo\nthree\nfour"
    assert file_result["kind"] == "file"
    assert file_result["truncated"] is False

    function_result = query.get_code_slice("fn_sample", kind="function")
    assert function_result["source"] == "two\nthree"
    assert query.get_code_slice("fn_sample", kind="class") is None

    def fail_if_read(*args, **kwargs):
        raise AssertionError("include_source=False must not perform file IO")

    monkeypatch.setattr(query, "_read_file_slice", fail_if_read)
    metadata = query.get_code_slice("fn_sample", include_source=False)
    assert metadata["source"] is None


def test_get_code_slice_kind_disambiguates_same_name(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    store = JsonStore(tmp_path / "graph")
    symbols = SymbolIndex()
    store.add_node({"id": "file_same", "type": "file", "path": "same.py"})
    store.add_node({
        "id": "cls_same", "type": "class", "name": "Same",
        "file_id": "file_same", "line_start": 1, "line_end": 2,
    })
    store.add_node({
        "id": "fn_same", "type": "function", "name": "Same",
        "file_id": "file_same", "line_start": 4, "line_end": 5,
    })
    # Class ranks first for an untyped lookup; ``kind`` must still select the
    # function rather than rejecting the first generic match.
    symbols.add("Same", "cls_same")
    symbols.add("Same", "fn_same")
    query = QueryEngine(
        store, KeywordIndex(), symbols, FileIndex(), project_path=str(project)
    )

    result = query.get_code_slice("Same", kind="function", include_source=False)

    assert result is not None
    assert result["target"] == "fn_same"
    assert result["kind"] == "function"


def test_get_code_slice_document_section_and_bounded_streaming(tmp_path, monkeypatch):
    project = tmp_path / "project"
    docs = project / "docs"
    docs.mkdir(parents=True)
    (docs / "guide.md").write_text(
        "# Guide\nintro\n## Details\nalpha\nbeta\ngamma\n",
        encoding="utf-8",
    )
    store = JsonStore(tmp_path / "graph")
    keyword = KeywordIndex()
    symbols = SymbolIndex()
    files = FileIndex()
    store.add_node({
        "id": "doc_guide",
        "type": "document",
        "title": "Guide",
        "path": "docs/guide.md",
        "line_count": 6,
    })
    store.add_node({
        "id": "sec_details",
        "type": "section",
        "title": "Details",
        "doc_id": "doc_guide",
        "line_start": 3,
        "line_end": 6,
    })
    files.add("docs/guide.md", {
        "file_id": "doc_guide",
        "kind": "document",
        "nodes": ["sec_details"],
    })
    query = QueryEngine(
        store, keyword, symbols, files, project_path=str(project)
    )

    section = query.get_code_slice(
        "docs/guide.md", kind="document", section="details"
    )
    assert section["kind"] == "section"
    assert section["content"] == "## Details\nalpha\nbeta\ngamma"

    monkeypatch.setattr(query, "MAX_CONTENT_LINES", 2)
    limited = query.get_code_slice("doc_guide")
    assert limited["source"] == "# Guide\nintro"
    assert limited["truncated"] is True

    monkeypatch.setattr(query, "MAX_CONTENT_LINES", 100)
    monkeypatch.setattr(query, "MAX_CONTENT_BYTES", 7)
    byte_limited = query.get_code_slice("doc_guide")
    assert len(byte_limited["source"].encode("utf-8")) <= 7
    assert byte_limited["truncated"] is True

    # A pathological minified file must be clipped while it is read, rather
    # than allocating the complete logical line before applying the budget.
    (docs / "guide.md").write_text("x" * 2_000_000 + "\ntail\n", encoding="utf-8")
    long_line = query.get_code_slice("doc_guide")
    assert long_line["source"] == "x" * 7
    assert long_line["truncated"] is True
    tail, truncated, last_line = query._read_file_slice("docs/guide.md", 2, 2)
    assert (tail, truncated, last_line) == ("tail", False, 2)


def test_get_code_slice_prefers_persisted_document_and_supports_ranges(tmp_path, monkeypatch):
    project = tmp_path / "project"
    docs = project / "docs"
    docs.mkdir(parents=True)
    (docs / "guide.md").write_text("live\nfile\nchanged\n", encoding="utf-8")
    snapshot = "one\ntwo needle\nthree\nfour"

    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_snapshot",
        "type": "document",
        "title": "Guide",
        "path": "docs/guide.md",
        "line_count": 4,
        "md5": "snapshot-md5",
        "content": snapshot,
        "content_complete": True,
    })
    store.add_node({
        "id": "sec_snapshot",
        "type": "section",
        "title": "Details",
        "doc_id": "doc_snapshot",
        "line_start": 2,
        "line_end": 3,
        "content": "legacy preview",
    })
    chunk_text = "two needle\nthree"
    chunk_start = snapshot.index(chunk_text)
    store.add_node({
        "id": "dchunk_snapshot",
        "type": "document_chunk",
        "doc_id": "doc_snapshot",
        "section_id": "sec_snapshot",
        "title": "Details",
        "line_start": 2,
        "line_end": 3,
        "char_start": chunk_start,
        "char_end": chunk_start + len(chunk_text),
        "content_preview": "unused",
    })
    files = FileIndex()
    files.add("docs/guide.md", {
        "file_id": "doc_snapshot", "kind": "document", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project)
    )

    whole = query.get_code_slice("doc_snapshot")
    assert whole["source"] == snapshot
    assert whole["content_source"] == "graph"
    assert whole["stored_complete"] is True
    assert whole["returned_complete"] is True
    assert whole["snapshot_md5"] == "snapshot-md5"

    live = query.get_code_slice("doc_snapshot", source="filesystem")
    assert live["source"] == "live\nfile\nchanged"
    assert live["content_source"] == "filesystem"

    section = query.get_code_slice("sec_snapshot", source="graph")
    assert section["content"] == chunk_text
    assert section["content_source"] == "graph"

    chunk = query.get_code_slice("dchunk_snapshot", source="graph")
    assert chunk["content"] == chunk_text

    selected = query.get_code_slice(
        "doc_snapshot", source="graph", line_start=2, line_end=3
    )
    assert selected["source"] == chunk_text
    assert selected["line_start"] == 2
    assert selected["line_end"] == 3

    monkeypatch.setattr(query, "MAX_CONTENT_LINES", 2)
    first = query.get_code_slice("doc_snapshot", source="graph")
    assert first["source"] == "one\ntwo needle\n"
    assert first["truncated"] is True
    assert first["next_line_start"] == 3
    second = query.get_code_slice(
        "doc_snapshot", source="graph", cursor=first["next_cursor"]
    )
    assert second["source"] == "three\nfour"
    assert second["returned_complete"] is True


def test_graph_section_page_does_not_split_a_dense_parent_snapshot(tmp_path):
    class DenseSnapshot(str):
        def splitlines(self, *args, **kwargs):  # pragma: no cover - must not run
            raise AssertionError("bounded graph paging must not split all lines")

    content = DenseSnapshot("row\n" * 120_000)
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_dense",
        "type": "document",
        "title": "Dense",
        "path": "docs/dense.md",
        "line_count": 120_000,
        "md5": "dense-snapshot",
        "content": content,
        "content_complete": True,
    })
    store.add_node({
        "id": "sec_dense",
        "type": "section",
        "title": "Late section",
        "doc_id": "doc_dense",
        "line_start": 119_999,
        "line_end": 119_999,
    })
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    result = query.get_code_slice("sec_dense", source="graph", max_bytes=8)

    assert result is not None
    assert result["content"] == "row"
    assert result["returned_complete"] is True


def test_get_code_slice_char_cursor_preserves_a_long_snapshot_line(tmp_path):
    content = "😀" + ("abcdef" * 7)
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_minified",
        "type": "document",
        "title": "Minified",
        "path": "docs/minified.json",
        "line_count": 1,
        "content": content,
        "content_complete": True,
    })
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    pages: list[str] = []
    cursor = None
    for _ in range(20):
        result = query.get_code_slice(
            "doc_minified", source="graph", max_bytes=7, cursor=cursor
        )
        assert result is not None
        pages.append(result["source"])
        if not result["truncated"]:
            assert result["returned_complete"] is True
            break
        assert result["next_line_start"] == 1
        assert result["next_cursor"].startswith("pb1.")
        cursor = result["next_cursor"]
    else:  # pragma: no cover - guards against a non-progressing cursor
        pytest.fail("snapshot cursor did not reach the end of the long line")

    assert "".join(pages) == content


def test_get_code_slice_preserves_terminal_newline_and_rejects_stale_cursor(
    tmp_path,
):
    store = JsonStore(tmp_path / "graph")
    document = {
        "id": "doc_newline",
        "type": "document",
        "title": "Newline",
        "path": "docs/newline.md",
        "line_count": 1,
        "md5": "old-md5",
        "content": "a\n",
        "content_complete": True,
    }
    store.add_node(document)
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    whole = query.get_code_slice("doc_newline", source="graph")
    assert whole["source"] == "a\n"
    assert whole["returned_complete"] is True

    first = query.get_code_slice(
        "doc_newline", source="graph", max_bytes=1
    )
    assert first["source"] == "a"
    assert first["truncated"] is True
    assert first["next_cursor"].startswith("pb1.")
    second = query.get_code_slice(
        "doc_newline", source="graph", max_bytes=1,
        cursor=first["next_cursor"],
    )
    assert first["source"] + second["source"] == "a\n"
    assert second["returned_complete"] is True

    changed = dict(document, content="changed\n", md5="new-md5")
    store.add_node(changed)
    assert query.get_code_slice(
        "doc_newline", source="graph", cursor=first["next_cursor"]
    ) is None


def test_get_code_slice_section_uses_opaque_line_cursor(tmp_path):
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_lines",
        "type": "document",
        "title": "Lines",
        "path": "docs/lines.md",
        "line_count": 3,
        "md5": "lines-md5",
        "content": "line1\nline2\nline3\n",
        "content_complete": True,
    })
    store.add_node({
        "id": "sec_lines",
        "type": "section",
        "doc_id": "doc_lines",
        "title": "Lines",
        "line_start": 1,
        "line_end": 3,
        "content": "",
    })
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    first = query.get_code_slice("sec_lines", source="graph", max_bytes=5)
    assert first["content"] == "line1"
    assert first["truncated"] is True
    assert first["next_cursor"].startswith("pb1.")
    second = query.get_code_slice(
        "sec_lines", source="graph", max_bytes=5,
        cursor=first["next_cursor"],
    )
    assert second["content"] == "line2"
    assert second["returned_line_end"] == 2

    ranged_first = query.get_code_slice(
        "doc_lines", source="graph", line_start=2, line_end=3,
        max_bytes=5,
    )
    assert ranged_first["source"] == "line2"
    ranged_second = query.get_code_slice(
        "doc_lines", source="graph", max_bytes=5,
        cursor=ranged_first["next_cursor"],
    )
    assert ranged_second["source"] == "line3"
    assert ranged_second["truncated"] is False
    assert ranged_second["returned_complete"] is True


def test_keyword_search_document_chunk_uses_parent_content_and_bounded_preview(tmp_path):
    store = JsonStore(tmp_path / "graph")
    content = "prefix " + ("a" * 300) + " NEEDLE " + ("z" * 300) + " suffix"
    store.add_node({
        "id": "doc_long",
        "type": "document",
        "title": "Long Guide",
        "path": "docs/long.md",
        "line_count": 1,
        "content": content,
        "content_complete": True,
    })
    chunk = {
        "id": "dchunk_long",
        "type": "document_chunk",
        "doc_id": "doc_long",
        "section_id": None,
        "title": "Long Guide",
        "line_start": 1,
        "line_end": 1,
        "char_start": 7,
        "char_end": len(content) - 7,
        "content_preview": "prefix only",
    }
    store.add_node(chunk)
    index = KeywordIndex()
    indexed = QueryEngine._index_text(chunk, store=store)
    assert "NEEDLE" in indexed
    assert "prefix " not in indexed
    index.add(chunk["id"], indexed)
    query = QueryEngine(store, index, SymbolIndex(), FileIndex())

    hit = query.keyword_search("needle", test_filter="all")[0]
    assert hit["id"] == "dchunk_long"
    assert hit["doc_id"] == "doc_long"
    assert hit["line_end"] == 1
    assert hit["content_available"] is True
    assert "needle" in hit["content_preview"].casefold()
    assert len(hit["content_preview"]) <= 200
    assert "content" not in hit


def test_empty_complete_document_is_a_graph_snapshot(tmp_path):
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_empty",
        "type": "document",
        "title": "Empty",
        "path": "docs/empty.md",
        "line_count": 0,
        "content": "",
        "content_complete": True,
    })
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    result = query.get_code_slice("doc_empty")
    assert result["source"] == ""
    assert result["content_source"] == "graph"
    assert result["stored_complete"] is True
    assert result["returned_complete"] is True


def test_get_code_slice_rejects_paths_outside_project(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    outside = tmp_path / "secret.txt"
    outside.write_text("secret", encoding="utf-8")
    store = JsonStore(tmp_path / "graph")
    files = FileIndex()
    store.add_node({
        "id": "file_secret",
        "type": "file",
        "path": "../secret.txt",
    })
    query = QueryEngine(
        store,
        KeywordIndex(),
        SymbolIndex(),
        files,
        project_path=str(project),
    )

    assert query.get_code_slice("file_secret") is None
    assert query.get_code_slice(str(outside)) is None


def test_filesystem_cursor_resumes_long_line_and_rejects_changed_file(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    source_path = project / "minified.json"
    content = "😀" + ("abcdef" * 5) + "\ntail\n"
    source_path.write_text(content, encoding="utf-8")
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_minified",
        "type": "file",
        "path": "minified.json",
        "line_count": 2,
    })
    files = FileIndex()
    files.add("minified.json", {
        "file_id": "file_minified", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project)
    )

    pages: list[str] = []
    cursor = None
    first_cursor = None
    for _ in range(20):
        page = query.get_code_slice(
            "file_minified", source="filesystem", max_bytes=7, cursor=cursor
        )
        assert page is not None
        pages.append(page["source"])
        if not page["truncated"]:
            break
        assert page["next_cursor"].startswith("pb1.")
        first_cursor = first_cursor or page["next_cursor"]
        cursor = page["next_cursor"]
    else:  # pragma: no cover
        pytest.fail("filesystem cursor did not make progress")

    assert "".join(pages) == content.rstrip("\n"), pages

    source_path.write_text("changed and longer", encoding="utf-8")
    assert query.get_code_slice(
        "file_minified", source="filesystem", cursor=first_cursor
    ) is None


def test_filesystem_cursor_fingerprints_the_file_opened_after_atomic_swap(
    tmp_path, monkeypatch,
):
    project = tmp_path / "project"
    project.mkdir()
    source_path = project / "swapped.txt"
    replacement_path = project / "replacement.txt"
    source_path.write_text("old", encoding="utf-8")
    replacement_path.write_text("replacement-content", encoding="utf-8")
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_swapped", "type": "file", "path": "swapped.txt",
        "line_count": 1,
    })
    files = FileIndex()
    files.add("swapped.txt", {
        "file_id": "file_swapped", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )

    path_type = type(source_path)
    original_open = path_type.open
    swapped = False

    def swap_before_open(path, *args, **kwargs):
        nonlocal swapped
        if path == source_path and not swapped:
            replacement_path.replace(source_path)
            swapped = True
        return original_open(path, *args, **kwargs)

    monkeypatch.setattr(path_type, "open", swap_before_open)

    first = query.get_code_slice(
        "file_swapped", source="filesystem", max_bytes=4,
    )
    assert first["source"] == "repl"
    assert first["truncated"] is True
    payload = _decode_content_cursor(first["next_cursor"])
    assert payload is not None
    assert len(payload["f"].split(":")) == 5

    second = query.get_code_slice(
        "file_swapped", source="filesystem", max_bytes=4,
        cursor=first["next_cursor"],
    )
    assert second is not None
    assert second["source"] == "acem"


def test_filesystem_cursor_rejects_file_changed_during_page_read(
    tmp_path, monkeypatch,
):
    project = tmp_path / "project"
    project.mkdir()
    source_path = project / "changing.txt"
    source_path.write_text("abcdefghij", encoding="utf-8")
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_changing", "type": "file", "path": "changing.txt",
        "line_count": 1,
    })
    files = FileIndex()
    files.add("changing.txt", {
        "file_id": "file_changing", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )
    first = query.get_code_slice(
        "file_changing", source="filesystem", max_bytes=4,
    )
    assert first["truncated"] is True

    import project_brain.query.engine as engine_module

    real_fstat = engine_module.os.fstat
    calls = 0

    def changing_fstat(file_descriptor):
        nonlocal calls
        current = real_fstat(file_descriptor)
        calls += 1
        if calls == 2:
            return SimpleNamespace(
                st_dev=current.st_dev,
                st_ino=current.st_ino,
                st_size=current.st_size,
                st_mtime_ns=current.st_mtime_ns,
                st_ctime_ns=current.st_ctime_ns + 1,
            )
        return current

    monkeypatch.setattr(engine_module.os, "fstat", changing_fstat)

    assert query.get_code_slice(
        "file_changing", source="filesystem", max_bytes=4,
        cursor=first["next_cursor"],
    ) is None
    assert calls == 2


@pytest.mark.parametrize(
    ("raw", "expected"),
    [(b"a\nb\n", "a\nb"), (b"a\r\nb\r\n", "a\nb")],
)
def test_filesystem_cursor_preserves_newlines_with_one_byte_pages(
    tmp_path, raw, expected
):
    project = tmp_path / "project"
    project.mkdir()
    (project / "tiny.txt").write_bytes(raw)
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_tiny", "type": "file", "path": "tiny.txt",
        "line_count": 2,
    })
    files = FileIndex()
    files.add("tiny.txt", {
        "file_id": "file_tiny", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )

    pages: list[str] = []
    cursor = None
    for _ in range(10):
        page = query.get_code_slice(
            "file_tiny", source="filesystem", max_bytes=1, cursor=cursor,
        )
        assert page is not None
        pages.append(page["source"])
        if not page["truncated"]:
            break
        cursor = page["next_cursor"]
    else:  # pragma: no cover
        pytest.fail("one-byte filesystem cursor did not make progress")

    assert "".join(pages) == expected, pages


def test_get_code_slice_rejects_oversized_cursor_before_decoding(tmp_path):
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_cursor", "type": "document", "path": "doc.md",
        "content": "snapshot", "content_complete": True,
    })
    query = QueryEngine(store, KeywordIndex(), SymbolIndex(), FileIndex())

    assert query.get_code_slice(
        "doc_cursor", source="graph", cursor="pb1." + ("A" * 9000),
    ) is None


def test_whole_filesystem_read_ignores_stale_graph_line_count(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    (project / "live.txt").write_text(
        "one\ntwo\nthree\n", encoding="utf-8",
    )
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_live", "type": "file", "path": "live.txt",
        "line_count": 1,
    })
    files = FileIndex()
    files.add("live.txt", {
        "file_id": "file_live", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )

    result = query.get_code_slice("file_live", source="filesystem")

    assert result["source"] == "one\ntwo\nthree"
    assert result["returned_line_end"] == 3
    assert result["returned_complete"] is True


def test_filesystem_invalid_utf8_respects_decoded_output_budget(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    (project / "invalid.bin").write_bytes(b"\xff" * 20)
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "file_invalid", "type": "file", "path": "invalid.bin",
        "line_count": 1,
    })
    files = FileIndex()
    files.add("invalid.bin", {
        "file_id": "file_invalid", "kind": "code", "nodes": [],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )

    pages: list[str] = []
    cursor = None
    for _ in range(30):
        page = query.get_code_slice(
            "file_invalid", source="filesystem", max_bytes=4, cursor=cursor,
        )
        pages.append(page["source"])
        assert len(page["source"].encode("utf-8")) <= 4
        if not page["truncated"]:
            break
        cursor = page["next_cursor"]
    else:  # pragma: no cover
        pytest.fail("invalid UTF-8 cursor did not make progress")

    assert "".join(pages) == "\ufffd" * 20


def test_converted_section_never_applies_canonical_lines_to_raw_file(tmp_path):
    project = tmp_path / "project"
    docs = project / "docs"
    docs.mkdir(parents=True)
    raw = "<h1>Raw title</h1>\n<p>raw one</p>\n<p>raw two</p>\n"
    (docs / "page.html").write_text(raw, encoding="utf-8")
    store = JsonStore(tmp_path / "graph")
    store.add_node({
        "id": "doc_converted",
        "type": "document",
        "title": "Converted",
        "path": "docs/page.html",
        "line_count": 1,
        "content": None,
        "content_complete": False,
        "content_representation": "converted_markdown",
    })
    store.add_node({
        "id": "sec_converted",
        "type": "section",
        "doc_id": "doc_converted",
        "title": "Canonical section",
        "line_start": 1,
        "line_end": 1,
        "content": "",
    })
    files = FileIndex()
    files.add("docs/page.html", {
        "file_id": "doc_converted",
        "kind": "document",
        "nodes": ["sec_converted"],
    })
    query = QueryEngine(
        store, KeywordIndex(), SymbolIndex(), files, project_path=str(project),
    )

    section = query.get_code_slice("sec_converted", source="filesystem")
    assert section["content"] is None
    assert section["content_source"] is None
    assert section["content_unavailable_reason"] == (
        "converted_document_section_requires_graph_snapshot"
    )

    whole = query.get_code_slice("doc_converted", source="filesystem")
    assert whole["source"] == raw.rstrip("\n")
    assert whole["returned_line_end"] == 3


def test_get_related_tests_inferred_from_callers(engine):
    engine.store.add_node({"id": "fn_z", "type": "function", "name": "do_z", "file_id": "file_1", "module_id": "mod_1", "line_start": 1, "is_test": False})
    engine.store.add_node({"id": "fn_tz", "type": "function", "name": "test_do_z", "file_id": "file_1", "module_id": "mod_1", "line_start": 10, "is_test": True})
    engine.store.add_edge(Edge(id="etz", type="CALL", source="fn_tz", target="fn_z"))
    engine.symbol_index.add("do_z", "fn_z")
    tests = engine.get_related_tests("fn_z")
    assert len(tests) == 1
    assert tests[0]["name"] == "test_do_z"


def test_hybrid_rrf_fusion(engine):
    class FakeSem:
        def available(self):
            return True

        def search(self, query, top_k):
            return [("fn_2", 0.9), ("fn_3", 0.8)]

        def __len__(self):
            return 2

    engine.semantic_index = FakeSem()
    engine.search_strategy = "hybrid"
    results = engine.keyword_search("order", top_k=5)
    ids = [r["id"] for r in results]
    assert "fn_2" in ids
    assert ids[0] == "fn_2"


def test_semantic_strategy_uses_semantic_only(engine):
    class FakeSem:
        def available(self):
            return True

        def search(self, query, top_k):
            return [("fn_3", 0.9)]

        def __len__(self):
            return 1

    engine.semantic_index = FakeSem()
    engine.search_strategy = "semantic"
    results = engine.keyword_search("order", top_k=5)
    ids = [r["id"] for r in results]
    assert ids == ["fn_3"]


def test_hybrid_fallback_when_semantic_empty(engine):
    engine.search_strategy = "hybrid"
    results = engine.keyword_search("order", top_k=5)
    assert results
    assert all("score" in r for r in results)


def test_index_text_node_types():
    assert QueryEngine._index_text({"type": "function", "name": "foo", "signature": "fn foo()", "docstring": "doc"}) == "foo fn foo() doc"
    assert QueryEngine._index_text({"type": "class", "name": "Bar", "docstring": "baz"}) == "Bar baz"
    assert QueryEngine._index_text({"type": "document", "title": "T", "path": "p.md"}) == "T p.md"
    assert QueryEngine._index_text({"type": "section", "title": "S", "content": "C"}) == "S C"
    assert QueryEngine._index_text({"type": "concept", "name": "X"}) == "X"
    assert QueryEngine._index_text({"type": "module", "name": "m"}) == "m"
    assert QueryEngine._index_text({"type": "file", "path": "x"}) is None


def test_index_text_function_body_optional():
    node = {"type": "function", "name": "f", "signature": "f()", "docstring": None, "body": "x = 1"}
    assert "x = 1" not in QueryEngine._index_text(node, index_body=False)
    assert "x = 1" in QueryEngine._index_text(node, index_body=True)


def test_get_doc_links_returns_section(engine):
    engine.store.add_node({"id": "sec_1", "type": "section", "title": "Overview", "doc_id": "doc_1", "line_start": 10, "content": "about OrderService"})
    engine.store.add_edge(Edge(id="sec_1->cls_1:DESCRIBE", type="DESCRIBE", source="sec_1", target="cls_1", properties={"method": "section"}))
    docs = engine.get_doc_links("cls_1")
    types = [d["type"] for d in docs]
    assert "document" in types
    assert "section" in types
    sec = [d for d in docs if d["type"] == "section"][0]
    assert sec["line"] == 10
    assert sec["path"] == "docs/order.md"