"""Tests for run_pipeline with real file input (--input-file / input_file)."""

from __future__ import annotations

from pathlib import Path

import pytest

from orxaq.orchestration.run import RunConfig, run_pipeline

FIXTURE_CSV = Path(__file__).parent.parent / "fixtures" / "fr_y14m_sample.csv"


class TestRunConfigInputFile:
    def test_input_file_default_none(self) -> None:
        cfg = RunConfig(institution_id="TEST001")
        assert cfg.input_file is None

    def test_input_file_stored(self) -> None:
        cfg = RunConfig(institution_id="TEST001", input_file="/tmp/loans.csv")
        assert cfg.input_file == "/tmp/loans.csv"

    def test_input_file_accepts_none_explicitly(self) -> None:
        cfg = RunConfig(institution_id="TEST001", input_file=None)
        assert cfg.input_file is None


class TestRunPipelineWithInputFile:
    @pytest.fixture(scope="class")
    def file_result(self, tmp_path_factory):
        """Run pipeline with fixture CSV once for the class."""
        out = tmp_path_factory.mktemp("run_portfolio_out")
        cfg = RunConfig(
            institution_id="PORTF001",
            period="2026Q1",
            output_dir=str(out),
            n_loans=20,
            seed=42,
            include_fair_lending=False,
            input_file=str(FIXTURE_CSV),
        )
        return run_pipeline(cfg)

    def test_run_succeeds_with_csv(self, file_result) -> None:
        assert file_result is not None

    def test_output_files_produced(self, file_result) -> None:
        assert len(file_result.files) == 8

    def test_ecl_total_positive(self, file_result) -> None:
        assert file_result.ecl_total >= 0.0

    def test_audit_entries_nonzero(self, file_result) -> None:
        assert file_result.audit_entries > 0

    def test_institution_id_preserved(self, file_result) -> None:
        assert file_result.institution_id == "PORTF001"

    def test_output_dir_is_path(self, file_result) -> None:
        assert isinstance(file_result.output_dir, str)


class TestRunPipelineFileNotFound:
    def test_missing_file_raises(self, tmp_path) -> None:
        cfg = RunConfig(
            institution_id="ERR001",
            output_dir=str(tmp_path / "out"),
            input_file="/nonexistent/loans.csv",
            include_fair_lending=False,
        )
        with pytest.raises((FileNotFoundError, RuntimeError, Exception)):
            run_pipeline(cfg)


class TestRunPipelineSyntheticFallback:
    def test_no_input_file_uses_synthetic(self, tmp_path) -> None:
        """Without input_file, pipeline still runs with synthetic data."""
        cfg = RunConfig(
            institution_id="SYNTH001",
            output_dir=str(tmp_path / "out"),
            n_loans=30,
            seed=1,
            include_fair_lending=False,
        )
        result = run_pipeline(cfg)
        assert result.ecl_total >= 0.0
        assert len(result.files) == 8
