"""Scan-scope include/exclude: policy semantics, config plumbing, CLI flags."""

import logging

import pytest
from types import SimpleNamespace

import project_brain.__main__ as cli
from project_brain.build.builder import GraphBuildError
from project_brain.build.scanner import FileScanner, TrackedFilePolicy
from project_brain.config import Config, ConfigError
from project_brain.graph.generation import GenerationRepository
from project_brain.graph.json_store import JsonStore
from project_brain.watcher.reconciler import (
    GRAPH_CONFIG_FIELDS,
    compute_graph_config_digest,
)


@pytest.fixture
def scan_project(tmp_path):
    """A small project with code, docs, manifests, and always-excluded paths."""
    (tmp_path / "src" / "lib").mkdir(parents=True)
    (tmp_path / "docs" / "wiki").mkdir(parents=True)
    (tmp_path / "node_modules").mkdir()
    (tmp_path / "src" / "main.py").write_text("def main():\n    pass\n", encoding="utf-8")
    (tmp_path / "src" / "lib" / "util.rs").write_text("fn helper() {}\n", encoding="utf-8")
    (tmp_path / "docs" / "guide.md").write_text("# Guide\n", encoding="utf-8")
    (tmp_path / "docs" / "wiki" / "page.md").write_text("# Wiki\n", encoding="utf-8")
    (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
    (tmp_path / "node_modules" / "dep.py").write_text("x=1\n", encoding="utf-8")
    (tmp_path / ".hidden.md").write_text("# hidden\n", encoding="utf-8")
    return tmp_path


def _code_paths(project, **policy_kwargs):
    scanner = FileScanner(project, **policy_kwargs)
    return sorted(
        path.relative_to(project).as_posix() for path, _ in scanner.scan_code_files()
    )


def _doc_paths(project, **policy_kwargs):
    scanner = FileScanner(project, **policy_kwargs)
    return sorted(
        path.relative_to(project).as_posix() for path in scanner.scan_doc_files()
    )


# --- scanner semantics -----------------------------------------------------


def test_empty_include_admits_everything(scan_project):
    assert _code_paths(scan_project) == ["src/lib/util.rs", "src/main.py"]
    assert _doc_paths(scan_project) == [
        "docs/guide.md", "docs/wiki/page.md",
    ]


def test_include_segment_matches_any_depth(scan_project):
    # Bare segment name: everything under src/, at any depth.
    assert _code_paths(scan_project, include_patterns=["src"]) == [
        "src/lib/util.rs", "src/main.py",
    ]
    assert _doc_paths(scan_project, include_patterns=["src"]) == []
    # Documents respect the whitelist through tracked_kind as well.
    assert _doc_paths(scan_project, include_patterns=["docs"]) == [
        "docs/guide.md", "docs/wiki/page.md",
    ]


def test_include_glob_and_prefix_patterns(scan_project):
    assert _code_paths(scan_project, include_patterns=["src/**/*.rs"]) == [
        "src/lib/util.rs",
    ]
    assert _doc_paths(scan_project, include_patterns=["docs/wiki/"]) == [
        "docs/wiki/page.md",
    ]


def test_exclude_wins_over_include(scan_project):
    assert _code_paths(
        scan_project,
        include_patterns=["src"],
        exclude_patterns=["**/util.rs"],
    ) == ["src/main.py"]


def test_include_cannot_rescue_always_excluded_paths(scan_project):
    # Hidden files and root-level junk directories are excluded regardless
    # of the include whitelist.
    assert _doc_paths(
        scan_project, include_patterns=[".hidden.md", "**"],
    ) == ["docs/guide.md", "docs/wiki/page.md"]
    assert _code_paths(
        scan_project, include_patterns=["node_modules"],
    ) == []


def test_manifests_bypass_include_whitelist(scan_project):
    scanner = FileScanner(scan_project, include_patterns=["docs"])
    manifests = sorted(
        path.relative_to(scan_project).as_posix()
        for path in scanner.scan_manifest_files()
    )
    assert manifests == ["pyproject.toml"]


def test_should_track_respects_include(scan_project):
    policy = TrackedFilePolicy(scan_project, include_patterns=["docs"])
    assert policy.should_track("docs/guide.md") is True
    assert policy.should_track("src/main.py") is False
    # Directories are not pruned by the whitelist (only files are filtered).
    assert policy.should_exclude("src") is False


# --- pattern anchoring: trailing slash = root prefix, bare = any depth ----


@pytest.fixture
def nested_project(tmp_path):
    """Root-level junk dirs vs same-named nested source dirs."""
    (tmp_path / "build").mkdir()  # root packaging junk
    (tmp_path / "src" / "build").mkdir(parents=True)  # nested source package
    (tmp_path / "src" / "core").mkdir(parents=True)
    (tmp_path / "packages" / "app" / "src").mkdir(parents=True)
    (tmp_path / "packages" / "app" / "node_modules").mkdir(parents=True)
    (tmp_path / "build" / "artifact.py").write_text("junk = 1\n", encoding="utf-8")
    (tmp_path / "src" / "build" / "plugin.py").write_text(
        "def plugin():\n    pass\n", encoding="utf-8",
    )
    (tmp_path / "src" / "core" / "main.py").write_text(
        "def main():\n    pass\n", encoding="utf-8",
    )
    (tmp_path / "packages" / "app" / "src" / "lib.py").write_text(
        "x = 1\n", encoding="utf-8",
    )
    (tmp_path / "packages" / "app" / "node_modules" / "dep.js").write_text(
        "x = 1\n", encoding="utf-8",
    )
    return tmp_path


def test_default_excludes_keep_nested_source_dirs(nested_project):
    # Regression: the default exclude list used to swallow nested source
    # dirs sharing a name with root-level junk (src/build/, src/dist/, ...)
    # because "build/" was stripped to an any-depth bare segment. Root
    # build/ stays excluded and bare "node_modules" still matches the
    # nested packages/*/node_modules trees of JS monorepos.
    scanner = FileScanner(
        nested_project, exclude_patterns=Config.default().exclude_patterns,
    )
    assert sorted(
        path.relative_to(nested_project).as_posix()
        for path, _ in scanner.scan_code_files()
    ) == ["packages/app/src/lib.py", "src/build/plugin.py", "src/core/main.py"]


def test_trailing_slash_pattern_is_root_anchored(nested_project):
    # "build/" (with slash) matches only the root-level build/ directory.
    policy = TrackedFilePolicy(nested_project, exclude_patterns=["build/"])
    assert policy.should_exclude("build/artifact.py") is True
    assert policy.should_exclude("src/build/plugin.py") is False
    # Bare "build" matches the segment at any depth.
    policy = TrackedFilePolicy(nested_project, exclude_patterns=["build"])
    assert policy.should_exclude("src/build/plugin.py") is True


def test_bare_pattern_matches_nested_node_modules(nested_project):
    policy = TrackedFilePolicy(nested_project, exclude_patterns=["node_modules"])
    assert policy.should_exclude("packages/app/node_modules/dep.js") is True


def test_include_prefix_is_root_anchored_too(nested_project):
    policy = TrackedFilePolicy(nested_project, include_patterns=["src/"])
    assert policy.should_track("src/core/main.py") is True
    # "src/" is a root-anchored prefix: a nested packages/app/src/ tree is
    # outside the whitelist. Bare "src" would admit both.
    assert policy.should_track("packages/app/src/lib.py") is False
    policy = TrackedFilePolicy(nested_project, include_patterns=["src"])
    assert policy.should_track("packages/app/src/lib.py") is True


# --- config plumbing -------------------------------------------------------


def test_default_include_patterns_empty_and_roundtrip(tmp_path):
    config = Config.default()
    assert config.include_patterns == []

    config.include_patterns = ["src/**", "docs/*.md"]
    config.save(str(tmp_path))
    reloaded = Config.load(str(tmp_path))
    assert reloaded.include_patterns == ["src/**", "docs/*.md"]


def test_validate_rejects_unsafe_scan_patterns(tmp_path):
    for bad in ("../outside", "src/../lib", "/absolute/x.py", "  "):
        config = Config.default()
        config.include_patterns = [bad]
        with pytest.raises(ConfigError, match=r"project\.include"):
            config.save(str(tmp_path))
        config = Config.default()
        config.exclude_patterns = [bad]
        with pytest.raises(ConfigError, match=r"project\.exclude"):
            config.save(str(tmp_path))


def test_include_patterns_participate_in_config_digest():
    base = Config.default()
    narrowed = Config.default()
    narrowed.include_patterns = ["src/**"]
    assert "include_patterns" in GRAPH_CONFIG_FIELDS
    assert compute_graph_config_digest(base) != compute_graph_config_digest(narrowed)


def test_load_warns_on_legacy_trailing_slash_exclude_patterns(tmp_path, caplog):
    # Configs saved before root-anchoring relied on any-depth matching for
    # single-segment trailing-slash patterns; loading them must surface the
    # scope change instead of passing silently.
    pb_dir = tmp_path / ".botbrain"
    pb_dir.mkdir()
    (pb_dir / "config.yaml").write_text(
        "project:\n"
        "  exclude: [node_modules/, build/, artifacts/, .venv/, docs/wiki/]\n",
        encoding="utf-8",
    )

    with caplog.at_level(logging.WARNING, logger="project_brain.config"):
        Config.load(str(tmp_path))

    message = caplog.text
    # Single-segment trailing-slash names warn...
    for pattern in ("node_modules/", "build/", "artifacts/"):
        assert repr(pattern) in message
    # ...hidden names (any-depth rule unchanged) and multi-segment prefixes
    # (already root-anchored before the fix) do not.
    assert ".venv/" not in message
    assert "docs/wiki/" not in message
    assert "any depth" in message


def test_load_fresh_default_save_does_not_warn(tmp_path, caplog):
    # A config saved by the current version carries the intended
    # root-anchored defaults; reloading it stays silent.
    Config.default().save(str(tmp_path))

    with caplog.at_level(logging.WARNING, logger="project_brain.config"):
        Config.load(str(tmp_path))

    assert "root-level" not in caplog.text


# --- CLI flags -------------------------------------------------------------


def _scan_flag_project(tmp_path):
    """A tiny project plus a keyword-strategy config with a pre-set exclude."""
    (tmp_path / "sample.py").write_text("def sample():\n    return 1\n", encoding="utf-8")
    (tmp_path / "docs").mkdir()
    (tmp_path / "docs" / "note.md").write_text("# Note\n", encoding="utf-8")
    # Keyword strategy avoids a semantic index build in unit tests.
    pb_dir = tmp_path / ".botbrain"
    pb_dir.mkdir(exist_ok=True)
    (pb_dir / "config.yaml").write_text(
        "search:\n  strategy: keyword\nproject:\n  exclude: [legacy/]\n",
        encoding="utf-8",
    )
    return pb_dir


def _graph_document_and_file_paths(pb_dir):
    """Relative paths of document/file nodes in the currently published graph."""
    graph_dir = GenerationRepository(pb_dir / "graph").current_path()
    store = JsonStore(graph_dir)
    store.load(str(graph_dir))
    return (
        sorted(node["path"] for node in store.get_nodes_by_type("document")),
        sorted(node["path"] for node in store.get_nodes_by_type("file")),
    )


def test_build_include_exclude_flags_are_ephemeral(tmp_path):
    # --include/--exclude are optional per-invocation flags: they narrow the
    # build that received them but are never written back to config.yaml.
    pb_dir = _scan_flag_project(tmp_path)
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=None,
        include=["docs/**"],
        exclude=["generated/"],
    )

    cli._cmd_build(tmp_path, args)

    # The flags shaped this build's graph scope...
    document_paths, file_paths = _graph_document_and_file_paths(pb_dir)
    assert document_paths == ["docs/note.md"]
    assert file_paths == []  # sample.py is outside the docs/** whitelist
    # ...but the config file kept its own scan scope.
    reloaded = Config.load(str(tmp_path))
    assert reloaded.include_patterns == []
    assert reloaded.exclude_patterns == ["legacy/"]


def test_scan_flags_do_not_leak_into_config_saved_by_other_flags(tmp_path):
    # A save triggered by a durable flag (--store-doc-content) must not
    # persist the ephemeral scan-scope overrides alongside it.
    pb_dir = _scan_flag_project(tmp_path)
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=["docs/**/*.md"],
        include=["docs/**"],
        exclude=["generated/"],
    )

    cli._cmd_build(tmp_path, args)

    reloaded = Config.load(str(tmp_path))
    assert reloaded.document_content_include == ["docs/**/*.md"]
    assert reloaded.include_patterns == []
    assert reloaded.exclude_patterns == ["legacy/"]


def test_build_rejects_unsafe_include_pattern(tmp_path):
    (tmp_path / "sample.py").write_text("x=1\n", encoding="utf-8")
    pb_dir = tmp_path / ".botbrain"
    pb_dir.mkdir(exist_ok=True)
    (pb_dir / "config.yaml").write_text(
        "search:\n  strategy: keyword\n", encoding="utf-8",
    )
    args = SimpleNamespace(include=["../outside.py"], exclude=None)

    with pytest.raises(ConfigError, match=r"project\.include"):
        cli._cmd_build(tmp_path, args)


def test_failed_build_does_not_persist_scan_patterns(tmp_path):
    docs = tmp_path / "docs"
    docs.mkdir()
    (docs / "large.md").write_text("# Large\n" + ("x" * 100), encoding="utf-8")
    config = Config.default()
    config.document_content_max_total_bytes = 1
    config.save(str(tmp_path))
    args = SimpleNamespace(
        semantic=False,
        index_body=False,
        precision=None,
        store_doc_content=["docs/**/*.md"],
        include=["docs/**"],
        exclude=["generated/"],
    )

    with pytest.raises(GraphBuildError, match="max_total_bytes"):
        cli._cmd_build(tmp_path, args)

    reloaded = Config.load(str(tmp_path))
    assert reloaded.include_patterns == []
    assert ".git/" in reloaded.exclude_patterns