"""Tests for the fallback code_chunk mechanism.

When a code file fails to tree-sitter parse, the builder installs a minimal
FileNode + line-windowed CodeChunkNodes so the file is still discoverable via
keyword_search / get_content / get_file_symbols.
"""
from __future__ import annotations

from pathlib import Path

import pytest

from project_brain.build.builder import GraphBuilder, build_has_failures
from project_brain.build.code_parser import LANGUAGE_RULES
from project_brain.build.languages.base import ParseError
from project_brain.config import Config
from project_brain.graph.json_store import JsonStore
from project_brain.query.engine import QueryEngine
from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex


# A Python file used to exercise the generic fallback path. Python now retains
# useful tree-sitter recovery evidence, so the module fixture below simulates a
# hard parser/runtime failure for this explicit marker. We still include
# identifiers so fallback chunks are keyword-searchable.
_BROKEN_PY = '''\
def broken_function(alpha, beta):
    """This function is fine but the file has a syntax error at the end."""
    result = alpha + beta
    return result

def another_function(gamma):
    delta = gamma * 2
    return delta

class BrokenClass:
    """A class in a broken file."""
    def method_one(self, epsilon):
        zeta = epsilon + 1
        return zeta

[[[ unterminated bracket that breaks tree-sitter
'''

# More than 120 lines so chunking produces multiple chunks.
_LONG_BROKEN_PY = "\n".join(
    f"def func_{i}(arg_{i}):  # broken syntax intentionally\n    return arg_{i}"
    for i in range(150)
) + "\n[[[ unterminated"


@pytest.fixture(autouse=True)
def force_hard_parser_failure_for_fallback_markers(monkeypatch):
    original_parse = LANGUAGE_RULES["python"].parse

    def parse(source: bytes, file_path: str):
        if b"unterminated" in source:
            raise ParseError(f"simulated hard parser failure in {file_path}")
        return original_parse(source, file_path)

    monkeypatch.setattr(LANGUAGE_RULES["python"], "parse", parse)


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


def _engine(project: Path, store, keyword, symbols, files):
    return QueryEngine(store, keyword, symbols, files, project_path=str(project))


def test_fallback_file_node_created_on_parse_failure(tmp_path):
    """A parse-failed file gets a FileNode + CodeChunkNodes."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")
    (project / "good.py").write_text("def ok():\n    return 42\n", encoding="utf-8")

    builder, store, keyword = _builder(project)
    builder.build_all(persist=False)

    # The file node should exist despite the parse failure.
    file_nodes = store.get_nodes_by_type("file")
    paths = {n["path"] for n in file_nodes}
    assert "broken.py" in paths, "fallback FileNode missing for parse-failed file"
    assert "good.py" in paths
    broken = next(node for node in file_nodes if node["path"] == "broken.py")
    assert broken["parse_status"] == "fallback"
    assert broken["parse_coverage"] == 0.0
    assert broken["parse_diagnostics"][0]["kind"] == "parser_error"

    # CodeChunkNodes should exist for the broken file.
    chunks = [n for n in store.get_nodes_by_type("code_chunk") if n.get("kind") == "fallback"]
    assert len(chunks) >= 1, "no fallback CodeChunkNodes created"
    assert all(n["source_id"].startswith("file_") for n in chunks)
    assert all(isinstance(n.get("content"), str) and n["content"] for n in chunks)


def test_fallback_chunks_have_line_ranges(tmp_path):
    """Fallback chunks record 1-based line_start/line_end."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, _ = _builder(project)
    builder.build_all(persist=False)

    chunks = [n for n in store.get_nodes_by_type("code_chunk") if n.get("kind") == "fallback"]
    for chunk in chunks:
        assert chunk["line_start"] >= 1
        assert chunk["line_end"] >= chunk["line_start"]
        # Content should correspond to the line range.
        lines = _BROKEN_PY.splitlines()
        expected = "\n".join(lines[chunk["line_start"] - 1: chunk["line_end"]])
        assert chunk["content"] == expected


def test_long_file_produces_multiple_chunks(tmp_path):
    """A file >120 lines produces multiple overlapping chunks."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "long_broken.py").write_text(_LONG_BROKEN_PY, encoding="utf-8")

    builder, store, _ = _builder(project)
    builder.build_all(persist=False)

    chunks = [n for n in store.get_nodes_by_type("code_chunk") if n.get("source_id", "").startswith("file_")]
    assert len(chunks) >= 2, f"expected multiple chunks, got {len(chunks)}"


def test_fallback_chunk_keyword_search(tmp_path):
    """keyword_search finds identifiers in the fallback chunks."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, keyword = _builder(project)
    builder.build_all(persist=False)
    # Rebuild indexes so the code_chunk text is in the BM25 index.
    builder.rebuild_bm25_index(load_existing=False)
    builder.rebuild_symbol_file_indexes()

    engine = _engine(project, store, keyword, builder.symbol_index, builder.file_index)
    results = engine.keyword_search("broken_function", top_k=10)
    # Should find a code_chunk containing "broken_function".
    chunk_hits = [r for r in results if r.get("type") == "code_chunk"]
    assert len(chunk_hits) >= 1, f"keyword_search did not find fallback chunk: {results}"


def test_fallback_chunk_get_content(tmp_path):
    """get_content returns the chunk's inline content by chunk id."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, keyword = _builder(project)
    builder.build_all(persist=False)
    builder.rebuild_bm25_index(load_existing=False)
    builder.rebuild_symbol_file_indexes()

    chunks = [n for n in store.get_nodes_by_type("code_chunk") if n.get("kind") == "fallback"]
    assert chunks
    chunk = chunks[0]

    engine = _engine(project, store, keyword, builder.symbol_index, builder.file_index)
    result = engine.get_code_slice(chunk["id"])
    assert result is not None, "get_code_slice returned None for a code_chunk"
    assert "content" in result
    # The returned content should contain the chunk's text.
    assert "broken_function" in result["content"] or "another_function" in result["content"]


def test_fallback_file_get_file_symbols(tmp_path):
    """get_file_symbols returns the chunk nodes for a parse-failed file."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, keyword = _builder(project)
    builder.build_all(persist=False)

    engine = _engine(project, store, keyword, builder.symbol_index, builder.file_index)
    symbols = engine.get_file_symbols("broken.py")
    # Should return the fallback chunk ids (not an empty list).
    assert len(symbols) >= 1, "get_file_symbols returned nothing for fallback file"
    assert all(s["type"] == "code_chunk" for s in symbols)


def test_fallback_build_still_reports_failures(tmp_path):
    """The build is still marked as having failures (degraded), but graph is usable."""
    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, _ = _builder(project)
    stats = builder.build_all(persist=False)

    assert stats["files_failed"] >= 1
    assert build_has_failures(stats)
    # But the file node exists (graph is usable).
    file_nodes = store.get_nodes_by_type("file")
    assert any(n["path"] == "broken.py" for n in file_nodes)


def test_fallback_in_subdir_links_to_parent_module(tmp_path):
    """Regression: a parse-failed file in a subdirectory is linked to its
    parent directory module. build_all previously raised
    ``AttributeError: 'JsonStore' object has no attribute 'get_edge'`` on this
    code path (code_parser.py fallback-linking loop), because ``get_edge`` was
    called but only ``get_edges`` was defined. The single-root-level broken
    files used elsewhere in this suite never enter that loop (no parent dir),
    so the bug only surfaced for fallback files nested in subdirectories —
    e.g. a real C codebase parsed with tree-sitter-c.
    """
    project = tmp_path / "project"
    project.mkdir()
    (project / "pkg").mkdir()
    # broken file nested in a subdir -> fallback node with a parent module
    (project / "pkg" / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")
    # a good sibling guarantees the "pkg" directory module node is created
    (project / "pkg" / "good.py").write_text("def ok():\n    return 42\n", encoding="utf-8")

    builder, store, _ = _builder(project)
    stats = builder.build_all(persist=False)  # must not raise AttributeError

    assert stats["files_failed"] >= 1
    assert build_has_failures(stats)
    file_nodes = store.get_nodes_by_type("file")
    paths = {n["path"].replace("\\", "/") for n in file_nodes}
    assert any(p.endswith("pkg/broken.py") for p in paths), paths


def test_fallback_content_preview(tmp_path):
    """_content_preview returns a preview for code_chunk nodes."""
    from project_brain.query.engine import _content_preview

    project = tmp_path / "project"
    project.mkdir()
    (project / "broken.py").write_text(_BROKEN_PY, encoding="utf-8")

    builder, store, _ = _builder(project)
    builder.build_all(persist=False)

    chunks = [n for n in store.get_nodes_by_type("code_chunk") if n.get("kind") == "fallback"]
    assert chunks
    preview = _content_preview(chunks[0], query="broken_function", store=store)
    assert preview is not None
    assert len(preview) > 0