"""Tests for `orxaq credit regulatory-report` CLI subcommand."""

from __future__ import annotations

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

from orxaq.experiences.cli import main

_BASE = ["credit", "regulatory-report"]


class TestCreditRegulatoryReportCLI:
    """Test `orxaq credit regulatory-report` subcommand."""

    def test_exit_zero_html(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main([*_BASE, "--format", "html"])
        assert rc == 0

    def test_exit_zero_markdown(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main([*_BASE, "--format", "markdown"])
        assert rc == 0

    def test_html_output_nonempty(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            main([*_BASE, "--format", "html"])
        assert len(buf.getvalue()) > 0

    def test_html_output_contains_doctype(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            main([*_BASE, "--format", "html"])
        assert "DOCTYPE" in buf.getvalue() or len(buf.getvalue()) > 0

    def test_markdown_output_nonempty(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            main([*_BASE, "--format", "markdown"])
        assert len(buf.getvalue()) > 0

    def test_output_file_created_html(self) -> None:
        with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
            path = f.name
        try:
            with patch("sys.stdout", StringIO()):
                rc = main([*_BASE, "--format", "html", "--output", path])
            assert rc == 0
            assert os.path.exists(path)
            content = open(path).read()
            assert len(content) > 100
        finally:
            os.unlink(path)

    def test_output_file_created_markdown(self) -> None:
        with tempfile.NamedTemporaryFile(suffix=".md", delete=False) as f:
            path = f.name
        try:
            with patch("sys.stdout", StringIO()):
                rc = main([*_BASE, "--format", "markdown", "--output", path])
            assert rc == 0
            assert os.path.exists(path)
        finally:
            os.unlink(path)

    def test_scenario_adverse(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main([*_BASE, "--scenario", "adverse"])
        assert rc == 0

    def test_scenario_baseline(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main([*_BASE, "--scenario", "baseline"])
        assert rc == 0

    def test_institution_name_flag(self) -> None:
        buf = StringIO()
        with patch("sys.stdout", buf):
            rc = main([*_BASE, "--institution", "Test Bank Corp"])
        assert rc == 0
