"""Tests for credit report CLI subcommand."""

from __future__ import annotations

import json
import os
import tempfile
from io import StringIO
from unittest.mock import patch

from orxaq.experiences.cli import main


class TestCreditReportCLI:
    """Test `orxaq credit report` subcommand."""

    def test_report_text_output(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["credit", "report"])
        assert rc == 0
        output = buf.getvalue()
        assert "Credit Risk Report" in output
        assert "Portfolio Risk Metrics" in output

    def test_report_json_output(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["--json", "credit", "report"])
        assert rc == 0
        data = json.loads(buf.getvalue())
        assert "report_id" in data
        assert "risk_rating" in data
        assert "sections" in data
        assert len(data["sections"]) == 4  # portfolio, ecl, stress, fairness

    def test_report_has_all_sections(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["--json", "credit", "report"])
        assert rc == 0
        data = json.loads(buf.getvalue())
        titles = [s["title"] for s in data["sections"]]
        assert "Portfolio Risk Metrics" in titles
        assert any("CECL" in t for t in titles)
        assert any("Stress" in t for t in titles)
        assert "Fair Lending Analysis" in titles

    def test_report_risk_rating_valid(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["--json", "credit", "report"])
        assert rc == 0
        data = json.loads(buf.getvalue())
        assert data["risk_rating"] in {"low", "moderate", "high", "critical"}

    def test_report_scenario_flag(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["--json", "credit", "report", "--scenario", "severely_adverse"])
        assert rc == 0
        data = json.loads(buf.getvalue())
        stress = [s for s in data["sections"] if "Stress" in s["title"]]
        assert len(stress) == 1
        assert "severely_adverse" in stress[0]["title"]

    def test_report_output_file(self) -> None:
        with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
            output_path = f.name
        try:
            buf = StringIO()
            with patch("sys.stdout", buf):
                rc = main(["credit", "report", "--output", output_path])
            assert rc == 0
            with open(output_path) as f:
                data = json.load(f)
            assert "report_id" in data
            assert "sections" in data
        finally:
            os.unlink(output_path)

    def test_report_baseline_scenario(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main(["--json", "credit", "report", "--scenario", "baseline"])
        assert rc == 0
        data = json.loads(buf.getvalue())
        assert data["risk_rating"] in {"low", "moderate", "high", "critical"}
