import pytest
from pathlib import Path
from project_brain.build.scanner import FileScanner, TrackedFilePolicy


@pytest.fixture
def sample_project(tmp_dir):
    """Create a sample project structure."""
    # Source files
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "main.py").write_text("print('hello')")
    (tmp_dir / "src" / "utils.ts").write_text("export function foo() {}")
    (tmp_dir / "src" / "lib.rs").write_text("fn main() {}")
    (tmp_dir / "src" / "app.c").write_text("int main() {}")

    # Test files
    (tmp_dir / "tests").mkdir()
    (tmp_dir / "tests" / "test_main.py").write_text("def test_foo(): pass")

    # Doc files
    (tmp_dir / "docs").mkdir()
    (tmp_dir / "docs" / "README.md").write_text("# Project")
    (tmp_dir / "README.md").write_text("# Root README")

    # Excluded files
    (tmp_dir / ".git").mkdir()
    (tmp_dir / ".git" / "config").write_text("git config")
    (tmp_dir / "__pycache__").mkdir()
    (tmp_dir / "__pycache__" / "main.cpython-310.pyc").write_text("bytecode")
    (tmp_dir / "node_modules").mkdir()
    (tmp_dir / "node_modules" / "pkg.js").write_text("module")

    return tmp_dir


def test_scan_code_files(sample_project):
    scanner = FileScanner(sample_project)
    files = list(scanner.scan_code_files())

    paths = [f[0].name for f in files]
    assert "main.py" in paths
    assert "utils.ts" in paths
    assert "lib.rs" in paths
    assert "app.c" in paths


def test_scan_excludes_git(sample_project):
    scanner = FileScanner(sample_project)
    files = list(scanner.scan_code_files())
    paths = [str(f[0]) for f in files]

    assert not any(".git" in p for p in paths)


def test_scan_excludes_pycache(sample_project):
    scanner = FileScanner(sample_project)
    files = list(scanner.scan_code_files())
    paths = [str(f[0]) for f in files]

    assert not any("__pycache__" in p for p in paths)


def test_scan_excludes_node_modules(sample_project):
    scanner = FileScanner(sample_project)
    files = list(scanner.scan_code_files())
    paths = [str(f[0]) for f in files]

    assert not any("node_modules" in p for p in paths)


def test_scan_doc_files(sample_project):
    scanner = FileScanner(sample_project)
    docs = list(scanner.scan_doc_files())

    names = [d.name for d in docs]
    assert "README.md" in names


def test_scan_symlink_files_keeps_inward_lexical_path_and_rejects_outbound(
    tmp_path,
):
    project = tmp_path / "project"
    docs = project / "docs"
    docs.mkdir(parents=True)
    inward_source = project / "document-source"
    inward_source.write_text("# Inward", encoding="utf-8")
    outside = tmp_path / "outside.md"
    outside.write_text("# Outside secret", encoding="utf-8")
    inward = docs / "inward.md"
    outbound = docs / "outbound.md"
    try:
        inward.symlink_to(inward_source)
        outbound.symlink_to(outside)
    except (NotImplementedError, OSError) as exc:
        pytest.skip(f"symlinks are unavailable on this platform: {exc}")

    paths = {
        path.relative_to(project).as_posix()
        for path in FileScanner(project).scan_doc_files()
    }

    assert "docs/inward.md" in paths
    assert "docs/outbound.md" not in paths


def test_scan_with_language_filter(sample_project):
    scanner = FileScanner(sample_project, languages=["python"])
    files = list(scanner.scan_code_files())

    langs = [f[1] for f in files]
    assert all(lang == "python" for lang in langs)


def test_cpp_only_policy_tracks_dot_h_as_cpp(tmp_dir):
    header = tmp_dir / "service.h"
    header.write_text("class Service {};", encoding="utf-8")
    scanner = FileScanner(tmp_dir, languages=["cpp"])

    files = list(scanner.scan_code_files())

    assert files == [(header, "cpp")]


def test_scan_with_custom_exclude(tmp_dir):
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "main.py").write_text("code")
    (tmp_dir / "generated").mkdir()
    (tmp_dir / "generated" / "auto.py").write_text("generated code")

    scanner = FileScanner(tmp_dir, exclude_patterns=["generated/"])
    files = list(scanner.scan_code_files())

    names = [f[0].name for f in files]
    assert "main.py" in names
    assert "auto.py" not in names


def test_scan_exclude_multi_segment_path(tmp_dir):
    """Multi-segment exclude patterns like 'demos/stm32f103ve/' must match."""
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "main.py").write_text("code")
    # Nested path to exclude
    (tmp_dir / "demos").mkdir()
    (tmp_dir / "demos" / "stm32f103ve").mkdir()
    (tmp_dir / "demos" / "stm32f103ve" / "app.c").write_text("int main(){}")
    (tmp_dir / "demos" / "stm32f103ve" / "sub").mkdir()
    (tmp_dir / "demos" / "stm32f103ve" / "sub" / "deep.py").write_text("x=1")
    # A sibling demo dir that should NOT be excluded
    (tmp_dir / "demos").mkdir(exist_ok=True)
    (tmp_dir / "demos" / "other").mkdir()
    (tmp_dir / "demos" / "other" / "keep.rs").write_text("fn main(){}")

    scanner = FileScanner(tmp_dir, exclude_patterns=["demos/stm32f103ve/"])
    files = list(scanner.scan_code_files())
    names = [f[0].name for f in files]

    assert "main.py" in names
    assert "keep.rs" in names              # sibling not excluded
    assert "app.c" not in names            # nested under excluded path
    assert "deep.py" not in names          # deeper nesting also excluded


def test_scan_exclude_single_segment_any_depth(tmp_dir):
    """Single-segment patterns like 'tests' match at any depth, not just root."""
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "main.py").write_text("code")
    (tmp_dir / "src" / "tests").mkdir()
    (tmp_dir / "src" / "tests" / "inner.py").write_text("x=1")

    scanner = FileScanner(tmp_dir, exclude_patterns=["tests"])
    files = list(scanner.scan_code_files())
    names = [f[0].name for f in files]

    assert "main.py" in names
    assert "inner.py" not in names         # matched at non-root depth


def test_scan_exclude_glob_pattern(tmp_dir):
    """Glob patterns match against file name and relative path."""
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "main.py").write_text("code")
    (tmp_dir / "src" / "foo.generated.py").write_text("gen")
    (tmp_dir / "src" / "bar_pb2.py").write_text("pb")

    scanner = FileScanner(
        tmp_dir, exclude_patterns=["*.generated.*", "*_pb2.*"]
    )
    files = list(scanner.scan_code_files())
    names = [f[0].name for f in files]

    assert "main.py" in names
    assert "foo.generated.py" not in names
    assert "bar_pb2.py" not in names


def test_language_detection(sample_project):
    scanner = FileScanner(sample_project)
    files = dict(scanner.scan_code_files())

    assert files[sample_project / "src" / "main.py"] == "python"
    assert files[sample_project / "src" / "utils.ts"] == "typescript"
    assert files[sample_project / "src" / "lib.rs"] == "rust"
    assert files[sample_project / "src" / "app.c"] == "c"


def test_default_language_detection_treats_header_as_cpp_in_cpp_project(tmp_dir):
    (tmp_dir / "service.cpp").write_text("int service() { return 1; }")
    header = tmp_dir / "service.h"
    header.write_text("class Service {};")

    files = dict(FileScanner(tmp_dir).scan_code_files())

    assert files[header] == "cpp"


def test_header_only_cpp_syntax_is_not_forced_through_c_parser(tmp_dir):
    header = tmp_dir / "service.h"
    header.write_text("class Service { public: void run(); };")

    files = dict(FileScanner(tmp_dir).scan_code_files())

    assert files[header] == "cpp"


def test_mixed_project_header_ignores_cpp_keywords_in_comments_and_strings(tmp_dir):
    (tmp_dir / "legacy.c").write_text("int legacy(void) { return 0; }")
    (tmp_dir / "demo.cpp").write_text("int demo() { return 0; }")
    header = tmp_dir / "legacy.h"
    header.write_text(
        '/* freed using release(); class namespace */\n'
        'static const char *message = "using namespace api::detail";\n'
        'struct legacy;\n',
        encoding="utf-8",
    )

    files = dict(FileScanner(tmp_dir).scan_code_files())

    assert files[header] == "c"


def test_mixed_project_header_keeps_real_cpp_syntax_evidence(tmp_dir):
    (tmp_dir / "legacy.c").write_text("int legacy(void) { return 0; }")
    (tmp_dir / "demo.cpp").write_text("int demo() { return 0; }")
    header = tmp_dir / "service.h"
    header.write_text("namespace api { class Service {}; }", encoding="utf-8")

    files = dict(FileScanner(tmp_dir).scan_code_files())

    assert files[header] == "cpp"


def test_scan_raises_when_os_walk_is_incomplete(tmp_dir, monkeypatch):
    from project_brain.build import scanner as scanner_module

    def incomplete_walk(*args, **kwargs):
        kwargs["onerror"](PermissionError("temporarily inaccessible"))
        return []

    monkeypatch.setattr(scanner_module.os, "walk", incomplete_walk)

    with pytest.raises(OSError, match="project scan incomplete"):
        list(FileScanner(tmp_dir).scan_code_files())


def test_go_and_java_language_detection(tmp_dir):
    (tmp_dir / "main.go").write_text("package main")
    (tmp_dir / "src").mkdir()
    (tmp_dir / "src" / "App.java").write_text("package com.example;")

    files = dict(FileScanner(tmp_dir).scan_code_files())

    assert files[tmp_dir / "main.go"] == "go"
    assert files[tmp_dir / "src" / "App.java"] == "java"


def test_language_for_go_and_java(tmp_dir):
    policy = TrackedFilePolicy(tmp_dir)

    assert policy.language_for(tmp_dir / "x.go") == "go"
    assert policy.language_for(tmp_dir / "x.java") == "java"
    assert policy.language_for(tmp_dir / "x.gomod") is None


def test_go_and_java_manifests(tmp_dir):
    assert TrackedFilePolicy.is_manifest(tmp_dir / "go.mod") is True
    assert TrackedFilePolicy.is_manifest(tmp_dir / "pom.xml") is True
    assert TrackedFilePolicy.is_manifest(tmp_dir / "build.gradle") is False


def test_detect_crate_from_go_mod(tmp_dir):
    (tmp_dir / "go.mod").write_text(
        "module example.com/mystore\n\ngo 1.22\n",
        encoding="utf-8",
    )
    (tmp_dir / "internal").mkdir()
    source = tmp_dir / "internal" / "store.go"
    source.write_text("package store", encoding="utf-8")

    scanner = FileScanner(tmp_dir)

    assert scanner.detect_crate(source) == "example.com/mystore"


def test_detect_crate_from_pom_xml(tmp_dir):
    (tmp_dir / "pom.xml").write_text(
        "<project>\n"
        "  <parent>\n"
        "    <groupId>org.springframework</groupId>\n"
        "    <artifactId>spring-boot-starter-parent</artifactId>\n"
        "  </parent>\n"
        "  <artifactId>my-app</artifactId>\n"
        "</project>\n",
        encoding="utf-8",
    )
    source = tmp_dir / "src" / "main" / "java" / "App.java"
    source.parent.mkdir(parents=True)
    source.write_text("package com.example;", encoding="utf-8")

    scanner = FileScanner(tmp_dir)

    # The <parent> artifactId must be skipped in favor of the project's own.
    assert scanner.detect_crate(source) == "my-app"


# ---------- read_file_text encoding detection ----------

def test_read_file_text_utf8(tmp_path):
    """Plain UTF-8 file reads correctly."""
    from project_brain.build.scanner import read_file_text
    f = tmp_path / "utf8.rs"
    f.write_bytes("fn hello() {}".encode("utf-8"))
    assert read_file_text(f) == "fn hello() {}"


def test_read_file_text_utf8_bom(tmp_path):
    """UTF-8 with BOM: BOM stripped, content decoded."""
    from project_brain.build.scanner import read_file_text
    f = tmp_path / "bom.c"
    f.write_bytes(b"\xef\xbb\xbfint main() {}")
    text = read_file_text(f)
    assert not text.startswith("\ufeff")  # BOM stripped
    assert "int main" in text


def test_read_file_text_gbk(tmp_path):
    """GBK-encoded file (Windows Chinese) decodes correctly."""
    from project_brain.build.scanner import read_file_text
    f = tmp_path / "gbk.c"
    # "函数" in GBK
    f.write_bytes(b"// \xba\xaf\xca\xfd\nint func() {}")
    text = read_file_text(f)
    assert "int func" in text
    assert "函数" in text  # GBK decoded correctly


def test_read_file_text_invalid_bytes_no_crash(tmp_path):
    """Garbage bytes never crash — replace with '?'."""
    from project_brain.build.scanner import read_file_text
    f = tmp_path / "bad.c"
    f.write_bytes(b"int \xff\xfe\x01 func() {}")
    text = read_file_text(f)
    assert "int" in text
    assert "func" in text  # ASCII parts survive