"""File I/O and validation."""

from collections.abc import Sequence
from pathlib import Path

from noisegate.models import Report

_MAX_CHARS = 100_000


def load_report(path: str) -> Report:
    """Load a single bug report file from disk."""
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"Report file not found: {path}")

    text = p.read_text(encoding="utf-8", errors="replace")
    if len(text) > _MAX_CHARS:
        text = text[:_MAX_CHARS]

    return Report(
        raw_text=text,
        source_path=str(p.resolve()),
        char_count=len(text),
    )


def load_reports(paths: Sequence[str]) -> Report:
    """Load one or more report files, combining them into a single Report.

    When multiple files are provided, each is labelled by filename and
    separated by a horizontal rule so the LLM can distinguish sections
    (e.g. writeup vs. PoC).
    """
    if len(paths) == 1:
        return load_report(paths[0])

    parts: list[str] = []
    for path in paths:
        p = Path(path)
        if not p.exists():
            raise FileNotFoundError(f"Report file not found: {path}")
        text = p.read_text(encoding="utf-8", errors="replace")
        if len(text) > _MAX_CHARS:
            text = text[:_MAX_CHARS]
        parts.append(f"## {p.name}\n\n{text}")

    combined = "\n\n---\n\n".join(parts)
    return Report(
        raw_text=combined,
        source_path=", ".join(str(Path(p).resolve()) for p in paths),
        char_count=len(combined),
    )
