"""Tests for file loading (loader.py)."""

from pathlib import Path

import pytest

from noisegate.loader import load_report, load_reports


def test_load_report(tmp_path: Path) -> None:
    report_file = tmp_path / "report.md"
    report_file.write_text("# XSS in login form\n\nDetails here.")

    doc = load_report(str(report_file))
    assert "XSS in login form" in doc.raw_text
    assert doc.char_count > 0
    assert str(report_file.resolve()) == doc.source_path


def test_load_report_missing() -> None:
    with pytest.raises(FileNotFoundError):
        load_report("/nonexistent/path/report.md")


def test_load_report_truncates_large_file(tmp_path: Path) -> None:
    report_file = tmp_path / "large.md"
    report_file.write_text("A" * 200_000)

    doc = load_report(str(report_file))
    assert doc.char_count == 100_000
    assert len(doc.raw_text) == 100_000


def test_load_reports_single_file_delegates(tmp_path: Path) -> None:
    f = tmp_path / "report.md"
    f.write_text("# XSS\n\nDetails.")
    doc = load_reports([str(f)])
    assert doc.raw_text == "# XSS\n\nDetails."
    assert doc.source_path == str(f.resolve())


def test_load_reports_multiple_files_combines(tmp_path: Path) -> None:
    writeup = tmp_path / "writeup.md"
    poc = tmp_path / "poc.py"
    writeup.write_text("# XSS writeup")
    poc.write_text("print('xss')")

    doc = load_reports([str(writeup), str(poc)])

    assert "## writeup.md" in doc.raw_text
    assert "# XSS writeup" in doc.raw_text
    assert "## poc.py" in doc.raw_text
    assert "print('xss')" in doc.raw_text
    assert "---" in doc.raw_text
    assert str(writeup.resolve()) in doc.source_path
    assert str(poc.resolve()) in doc.source_path


def test_load_reports_missing_file() -> None:
    with pytest.raises(FileNotFoundError):
        load_reports(["/nonexistent/report.md"])


def test_load_reports_missing_one_of_multiple(tmp_path: Path) -> None:
    real = tmp_path / "real.md"
    real.write_text("content")
    with pytest.raises(FileNotFoundError):
        load_reports([str(real), "/nonexistent/poc.py"])
