#!/usr/bin/env -S uv run --quiet --script
# /// script
# requires-python = ">=3.13"
# ///

# scan markdown/RST files for TODO comments

import sys
from pathlib import Path

SUFFIXES = (".md", ".rst")

# Skip some common large directories for performance reasons
SKIP_DIRS = {
    "node_modules",
    ".git",
    ".venv",
    ".tox",
    ".mypy_cache",
    ".ruff_cache",
    ".pytest_cache",
}

TODO_HIGHLIGHT = "\x1b[1;35m"
PATH_HIGHLIGHT = "\x1b[1;34m"
RESET = "\x1b[0m"


def iter_files(root):
    for current, dirs, files in root.walk():
        dirs[:] = [name for name in sorted(dirs) if name not in SKIP_DIRS]
        for name in sorted(files):
            if name.lower().endswith(SUFFIXES):
                yield current / name


def scan_file(path):
    with path.open(encoding="utf-8", errors="ignore") as file:
        for line_number, line in enumerate(file, start=1):
            if line.removeprefix(".. ").lstrip().startswith("TODO"):
                yield line_number, line.removesuffix("\n")


def highlight_todo(text):
    if not sys.stdout.isatty():
        return text
    return text.replace("TODO", f"{TODO_HIGHLIGHT}TODO{RESET}", count=1)


def highlight_path(text):
    if not sys.stdout.isatty():
        return text
    return f"{PATH_HIGHLIGHT}{text}{RESET}"


def main():
    found_any = False
    for path in iter_files(Path()):
        hits = list(scan_file(path))
        if not hits:
            continue

        # Print filename
        if found_any:
            print()
        found_any = True
        print(highlight_path(path))

        # Print matching lines
        for line_number, line in hits:
            print(f"{line_number:>3}: {highlight_todo(line)}")

    return int(found_any)  # success if no matches


if __name__ == "__main__":
    sys.exit(main())
