import pytest
import threading
import time
from pathlib import Path
from project_brain.graph.json_store import JsonStore
from project_brain.query.index import KeywordIndex, SymbolIndex, FileIndex
from project_brain.build.scanner import TrackedFilePolicy
from project_brain.watcher.updater import IncrementalUpdater
from project_brain.watcher.watcher import (
    WatcherManager,
    ProjectBrainWatcher,
    _PollingWatcher,
    _SimpleEvent,
)


@pytest.fixture
def setup(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    src = project / "src"
    src.mkdir()
    (src / "main.py").write_text("def hello():\n    pass\n")

    store = JsonStore(project / ".pb")
    kw_idx = KeywordIndex()
    sym_idx = SymbolIndex()
    file_idx = FileIndex()

    updater = IncrementalUpdater(store, kw_idx, sym_idx, file_idx, project)

    return {
        "project": project,
        "store": store,
        "updater": updater,
    }


def test_watcher_detects_change(setup):
    project = setup["project"]
    updater = setup["updater"]
    store = setup["store"]

    with WatcherManager(project, updater, debounce_seconds=0.5) as manager:
        time.sleep(0.2)
        (project / "src" / "main.py").write_text("def hello():\n    pass\n\ndef new_func():\n    pass\n")
        time.sleep(1.5)

    functions = store.get_nodes_by_type("function")
    fn_names = [f["name"] for f in functions]
    assert "new_func" in fn_names


def test_watcher_ignores_git(setup):
    project = setup["project"]
    updater = setup["updater"]

    handler = ProjectBrainWatcher(project, updater)
    assert handler._should_ignore(str(project / ".git" / "config")) is True
    assert handler._should_ignore(str(project / "src" / "main.py")) is False


def test_watcher_ignores_pycache(setup):
    project = setup["project"]
    updater = setup["updater"]

    handler = ProjectBrainWatcher(project, updater)
    assert handler._should_ignore(str(project / "__pycache__" / "main.pyc")) is True


class _RecordingUpdater:
    def __init__(self, file_index=None):
        self.batches = []
        self.file_index = file_index

    def update(self, paths):
        self.batches.append(list(paths))
        return len(paths)

    def handle_delete(self, path):
        raise AssertionError("deletes must go through the unified update batch")


class _DirectoryEvent:
    def __init__(self, src_path, dest_path=""):
        self.src_path = str(src_path)
        self.dest_path = str(dest_path) if dest_path else ""
        self.is_directory = True


def test_tracked_file_policy_normalizes_and_filters(tmp_path):
    project = tmp_path / "project"
    (project / "src").mkdir(parents=True)
    policy = TrackedFilePolicy(
        project,
        exclude_patterns=["src/generated/"],
        languages=["python"],
    )

    assert policy.normalize(project / "src" / "main.py") == "src/main.py"
    assert policy.should_track(project / "src" / "main.py") is True
    assert policy.should_track(project / "src" / "main.ts") is False
    assert policy.should_track(project / "README.md") is True
    assert policy.should_track(project / "src" / "generated" / "auto.py") is False
    assert policy.should_track(tmp_path / "outside.py") is False


def test_all_file_events_share_one_debounced_update_batch(tmp_path):
    project = tmp_path / "project"
    (project / "src").mkdir(parents=True)
    updater = _RecordingUpdater()
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)

    main = project / "src" / "main.py"
    main.write_text("x = 1")
    renamed = project / "src" / "renamed.py"
    renamed.write_text("x = 2")

    # Duplicate create/modify events collapse to one final-state path.
    handler.on_created(_SimpleEvent("created", str(main)))
    handler.on_modified(_SimpleEvent("modified", str(main)))
    handler.on_deleted(_SimpleEvent("deleted", str(project / "src" / "gone.py")))
    handler.on_moved(_SimpleEvent(
        "moved",
        str(project / "src" / "old.py"),
        str(renamed),
    ))
    handler.flush()

    assert updater.batches == [[
        "src/main.py",
        "src/gone.py",
        "src/old.py",
        "src/renamed.py",
    ]]


def test_event_storm_uses_one_resident_debounce_worker(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    changed = project / "changed.py"
    changed.write_text("x = 1")
    updater = _RecordingUpdater()
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)

    for _ in range(2000):
        handler.on_modified(_SimpleEvent("modified", str(changed)))
    worker = handler._worker
    assert worker is not None

    handler.flush(timeout=2)

    assert handler._worker is worker
    assert updater.batches == [["changed.py"]]
    assert handler.stop(timeout=2) is True


def test_directory_scan_failure_does_not_kill_debounce_worker(
    tmp_path, monkeypatch,
):
    project = tmp_path / "project"
    directory = project / "src"
    directory.mkdir(parents=True)
    updater = _RecordingUpdater()
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)
    original_expand = handler._expand_directory
    calls = {"count": 0}

    def flaky_expand(*args, **kwargs):
        calls["count"] += 1
        if calls["count"] == 1:
            raise PermissionError("synthetic scan failure")
        return original_expand(*args, **kwargs)

    monkeypatch.setattr(handler, "_expand_directory", flaky_expand)
    handler.on_created(_DirectoryEvent(directory))
    assert handler.flush(timeout=2) is True

    changed = directory / "later.py"
    changed.write_text("x = 1")
    handler.on_modified(_SimpleEvent("modified", str(changed)))
    assert handler.flush(timeout=2) is True

    assert updater.batches == [["src/later.py"]]
    assert handler._worker is not None and handler._worker.is_alive()
    assert handler.stop(timeout=2) is True


def test_stop_is_bounded_when_updater_is_blocked(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    changed = project / "changed.py"
    changed.write_text("x = 1")
    entered = threading.Event()
    release = threading.Event()

    class BlockingUpdater(_RecordingUpdater):
        def update(self, paths):
            entered.set()
            release.wait()
            return super().update(paths)

    handler = ProjectBrainWatcher(
        project, BlockingUpdater(), debounce_seconds=0,
    )
    handler.on_modified(_SimpleEvent("modified", str(changed)))
    assert entered.wait(1)

    started = time.monotonic()
    assert handler.stop(timeout=0.05) is False
    assert time.monotonic() - started < 0.5

    release.set()
    worker = handler._worker
    if worker is not None:
        worker.join(timeout=1)
    assert worker is None or not worker.is_alive()


def test_manager_propagates_handler_stop_timeout(tmp_path, monkeypatch):
    project = tmp_path / "project"
    project.mkdir()
    manager = WatcherManager(project, _RecordingUpdater())
    observed = {}

    def timed_out_stop(flush=True, timeout=5):
        observed.update(flush=flush, timeout=timeout)
        return False

    monkeypatch.setattr(manager.handler, "stop", timed_out_stop)

    assert manager.stop(timeout=0.25) is False
    assert observed["flush"] is True
    assert 0 <= observed["timeout"] <= 0.25


def test_deleted_directory_expands_all_indexed_descendants_into_one_batch(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    file_index = FileIndex()
    file_index.add("src/removed/a.py", {"file_id": "a", "nodes": []})
    file_index.add("src/removed/nested/README.md", {"file_id": "readme", "nodes": []})
    file_index.add("src/kept.py", {"file_id": "kept", "nodes": []})
    updater = _RecordingUpdater(file_index)
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)

    handler.on_deleted(_DirectoryEvent(project / "src" / "removed"))
    handler.flush()

    assert updater.batches == [[
        "src/removed/a.py",
        "src/removed/nested/README.md",
    ]]


def test_moved_directory_batches_indexed_sources_and_destination_files(tmp_path):
    project = tmp_path / "project"
    destination = project / "src" / "renamed"
    (destination / "nested").mkdir(parents=True)
    (destination / "a.py").write_text("x = 1")
    (destination / "nested" / "guide.md").write_text("# Guide")
    (destination / "ignored.bin").write_bytes(b"ignored")

    file_index = FileIndex()
    file_index.add("src/original/a.py", {"file_id": "a", "nodes": []})
    file_index.add(
        "src/original/nested/guide.md",
        {"file_id": "guide", "nodes": []},
    )
    updater = _RecordingUpdater(file_index)
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)

    handler.on_moved(_DirectoryEvent(project / "src" / "original", destination))
    handler.flush()

    assert updater.batches == [[
        "src/original/a.py",
        "src/original/nested/guide.md",
        "src/renamed/a.py",
        "src/renamed/nested/guide.md",
    ]]


def test_stop_flushes_pending_changes_and_rejects_late_events(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    updater = _RecordingUpdater()
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60)
    changed = project / "changed.py"
    changed.write_text("x = 1")

    handler.on_modified(_SimpleEvent("modified", str(changed)))
    handler.stop()
    handler.on_modified(_SimpleEvent("modified", str(changed)))

    assert updater.batches == [["changed.py"]]


def test_polling_full_scan_detects_deletion(tmp_path):
    project = tmp_path / "project"
    project.mkdir()
    deleted = project / "deleted.py"
    deleted.write_text("x = 1")
    updater = _RecordingUpdater()
    policy = TrackedFilePolicy(project)
    handler = ProjectBrainWatcher(project, updater, debounce_seconds=60, policy=policy)
    polling = _PollingWatcher(
        project,
        handler,
        full_scan_interval=1,
        policy=policy,
    )
    polling._known_files = polling._full_scan()

    deleted.unlink()
    polling._check_changes()
    handler.flush()

    assert updater.batches == [["deleted.py"]]


def test_native_and_polling_use_the_same_file_policy(tmp_path):
    project = tmp_path / "project"
    (project / "src" / "generated").mkdir(parents=True)
    python_file = project / "src" / "main.py"
    typescript_file = project / "src" / "main.ts"
    document = project / "README.md"
    generated = project / "src" / "generated" / "auto.py"
    for path in (python_file, typescript_file, document, generated):
        path.write_text("content")

    policy = TrackedFilePolicy(
        project,
        exclude_patterns=["src/generated/"],
        languages=["python"],
    )
    updater = _RecordingUpdater()
    handler = ProjectBrainWatcher(project, updater, policy=policy)
    polling = _PollingWatcher(project, handler, policy=policy)

    snapshot = set(polling._full_scan())
    assert snapshot == {"src/main.py", "README.md"}
    for path in (python_file, document):
        assert handler._should_ignore(str(path)) is False
    for path in (typescript_file, generated):
        assert handler._should_ignore(str(path)) is True