"""File loading utilities for SecAgent."""

from __future__ import annotations

import logging
from pathlib import Path

logger = logging.getLogger(__name__)


def read_file_lines(path: str | Path) -> list[str]:
    """Read a file and return its lines (preserving newlines).

    Returns an empty list if the file cannot be read.
    """
    try:
        return Path(path).read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)
    except OSError as exc:
        logger.warning("Cannot read %s: %s", path, exc)
        return []


def read_file_text(path: str | Path) -> str:
    """Return the full text content of *path*, or an empty string on failure."""
    try:
        return Path(path).read_text(encoding="utf-8", errors="replace")
    except OSError as exc:
        logger.warning("Cannot read %s: %s", path, exc)
        return ""


def collect_files(target: Path, extensions: set[str] | None = None) -> list[Path]:
    """Recursively collect files under *target*.

    Parameters
    ----------
    target:
        A file or directory path.
    extensions:
        Optional set of extensions (e.g. ``{".py", ".js"}``).  When provided,
        only files matching one of these extensions are returned.

    Returns
    -------
    list[Path]
        Sorted list of matching file paths.
    """
    if target.is_file():
        if extensions is None or target.suffix in extensions:
            return [target]
        return []

    results: list[Path] = []
    for p in sorted(target.rglob("*")):
        if p.is_file() and (extensions is None or p.suffix in extensions):
            results.append(p)
    return results
