"""AST parsing utilities for Python source files."""

from __future__ import annotations

import ast
from pathlib import Path


def parse_file(path: Path) -> ast.Module:
    """Parse a single Python source file into an AST.

    Args:
        path: Path to the .py file to parse.

    Returns:
        The parsed ast.Module.

    Raises:
        SyntaxError: If the file contains invalid Python.
        OSError: If the file cannot be read.
    """
    source = path.read_text(encoding="utf-8")
    return ast.parse(source, filename=str(path))


def parse_directory(path: Path) -> list[ast.Module]:
    """Recursively parse all Python files in a directory.

    Files that fail to parse are skipped with a warning rather than
    aborting the entire scan.

    Args:
        path: Root directory to scan.

    Returns:
        List of parsed ast.Module objects (one per successfully parsed file).
    """
    import warnings

    modules: list[ast.Module] = []
    for py_file in sorted(path.rglob("*.py")):
        try:
            modules.append(parse_file(py_file))
        except SyntaxError as exc:
            warnings.warn(
                f"Skipping {py_file}: syntax error — {exc}",
                stacklevel=2,
            )
    return modules
