#!/usr/bin/env python3
"""Run clangd diagnostics on an explicit list of C++ source files.

Usage:
    python3 tools/clangd-diag-files.py <file> [<file> ...]
"""

import subprocess
import sys
from pathlib import Path


def find_project_root():
    """Walk up from this script's directory to find the project root."""
    d = Path(__file__).resolve().parent.parent
    if (d / "build.py").exists():
        return d
    return Path.cwd()


def run_diagnostics(root, rel_path):
    """Run clangd-query.py diagnostics on a single file. Returns output lines."""
    result = subprocess.run(
        [sys.executable, "tools/clangd-query.py", "diagnostics", str(rel_path)],
        cwd=root,
        capture_output=True,
        text=True,
        timeout=120,
    )
    output = result.stdout.strip()
    if result.returncode != 0 and result.stderr.strip():
        if output:
            output += "\n"
        output += result.stderr.strip()
    return output


def normalize_path(root, raw_path):
    """Normalize a user-provided path to a project-relative path."""
    path = Path(raw_path)
    if path.is_absolute():
        path = path.resolve().relative_to(root.resolve())
    return path


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 tools/clangd-diag-files.py <file> [<file> ...]", file=sys.stderr)
        return 2

    root = find_project_root()
    files = [normalize_path(root, arg) for arg in sys.argv[1:]]

    total_issues = 0
    files_with_issues = 0

    for i, rel_path in enumerate(files):
        label = f"[{i + 1}/{len(files)}] {rel_path}"
        print(f"{label} ... ", end="", flush=True)

        try:
            output = run_diagnostics(root, rel_path)
        except subprocess.TimeoutExpired:
            print("TIMEOUT")
            continue

        if not output or "No problems found" in output or output.strip() == "No diagnostics.":
            print("ok")
            continue

        lines = [line for line in output.splitlines() if line.strip()]
        count = len(lines)
        total_issues += count
        files_with_issues += 1
        print(f"{count} issue(s)")
        for line in lines:
            print(f"  {line}")

    print(f"\nDone. {total_issues} issue(s) in {files_with_issues} file(s) out of {len(files)} checked.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
