"""Tests for CLI commands."""
from click.testing import CliRunner
from toil_tracker.cli import cli


class TestCLI:
    def test_demo_terminal(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["demo"])
        assert result.exit_code == 0
        assert "Toil" in result.output or "TOIL-" in result.output

    def test_demo_json(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["demo", "--format", "json"])
        assert result.exit_code == 0
        assert "health_score" in result.output
        assert "findings" in result.output

    def test_demo_html(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["demo", "--format", "html"])
        assert result.exit_code == 0
        assert "<html>" in result.output

    def test_rules_command(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["rules"])
        assert result.exit_code == 0
        assert "Toil Analysis Rules" in result.output

    def test_analyze_file(self, tmp_path, sample_inventory_yaml):
        inv = tmp_path / "toil.yaml"
        inv.write_text(sample_inventory_yaml)
        runner = CliRunner()
        result = runner.invoke(cli, ["analyze", str(inv)])
        assert result.exit_code == 0

    def test_analyze_json(self, tmp_path, sample_inventory_yaml):
        inv = tmp_path / "toil.yaml"
        inv.write_text(sample_inventory_yaml)
        runner = CliRunner()
        result = runner.invoke(cli, ["analyze", str(inv), "--format", "json"])
        assert result.exit_code == 0
        assert "health_score" in result.output

    def test_analyze_fail_on(self, tmp_path, sample_inventory_yaml):
        inv = tmp_path / "toil.yaml"
        inv.write_text(sample_inventory_yaml)
        runner = CliRunner()
        result = runner.invoke(cli, ["analyze", str(inv), "--fail-on", "high"])
        # daily deployment task should trigger TOIL-001 (critical) and TOIL-002 (high)
        assert result.exit_code == 1

    def test_analyze_output_file(self, tmp_path, sample_inventory_yaml):
        inv = tmp_path / "toil.yaml"
        inv.write_text(sample_inventory_yaml)
        out = tmp_path / "report.json"
        runner = CliRunner()
        result = runner.invoke(cli, ["analyze", str(inv), "--format", "json", "-o", str(out)])
        assert result.exit_code == 0
        assert out.exists()

    def test_help(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["--help"])
        assert result.exit_code == 0
        assert "toil-tracker" in result.output
