"""pjctx watch — Watch for file changes and auto-save context."""

from __future__ import annotations

import time

from pjctx.core.config import find_repo_root, get_pjctx_dir, load_config, load_ignore_patterns
from pjctx import ui


def run_watch(obj: dict, interval: int = 300) -> None:
    repo_root = find_repo_root()
    if repo_root is None:
        ui.error("Not inside a git repository.")
        raise SystemExit(1)

    if not get_pjctx_dir(repo_root).exists():
        ui.error("Not initialized. Run 'pjctx init' first.")
        raise SystemExit(1)

    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler

    ignore_patterns = {".pjctx", ".git"}
    config = load_config(repo_root)
    for pat in config.get("watch_ignore", []):
        ignore_patterns.add(pat)
    for pat in load_ignore_patterns(repo_root):
        ignore_patterns.add(pat)

    dirty = False
    last_save = time.time()

    class ChangeHandler(FileSystemEventHandler):
        def on_any_event(self, event):
            nonlocal dirty
            path = event.src_path
            # Skip ignored paths
            for pat in ignore_patterns:
                if pat in path:
                    return
            dirty = True

    handler = ChangeHandler()
    observer = Observer()
    observer.schedule(handler, str(repo_root), recursive=True)
    observer.start()

    ui.success(f"Watching for changes (auto-save every {interval}s)...")
    ui.info("Press Ctrl+C to stop.")

    try:
        while True:
            time.sleep(1)
            now = time.time()
            if dirty and (now - last_save) >= interval:
                dirty = False
                last_save = now
                _do_auto_save(repo_root)
    except KeyboardInterrupt:
        observer.stop()
        ui.info("\nStopped watching.")
    observer.join()


def _do_auto_save(repo_root) -> None:
    from pjctx.commands.save import run_save
    try:
        run_save({}, auto_mode=True)
    except SystemExit:
        pass
