import unittest
import unittest.mock
import json

from typer.testing import CliRunner

from nixprstatus.app import app

from tests.helpers.mocks import mocked_requests_get

runner = CliRunner()


class TestCli(unittest.TestCase):
    def test_help(self):
        result = runner.invoke(app, ["--help"])
        self.assertEqual(result.exit_code, 0)
        self.assertIn("Usage: root [OPTIONS] COMMAND [ARGS]...", result.output)
        self.assertIn("--show-completion", result.output)
        self.assertIn("Commands:", result.output)
        self.assertIn("pr", result.output)
        self.assertIn("watchlist", result.output)
        self.assertIn("since", result.output)

    def test_pr_help(self):
        result = runner.invoke(app, ["pr", "--help"])
        self.assertEqual(result.exit_code, 0)
        self.assertIn("Usage: root pr [OPTIONS] PR..", result.output)
        self.assertIn("Options:", result.output)

    @unittest.mock.patch("requests.get", side_effect=mocked_requests_get)
    def test_pr_single_simple(self, mock_get):
        result = runner.invoke(
            app,
            [
                "pr",
                "--format",
                "json",
                "--branches",
                "nixos-unstable-small",
                "--branches",
                "nixos-unstable",
                "--branches",
                "nixos-24.11",
                "345583",
            ],
        )
        print(result.exception)
        self.assertEqual(result.exit_code, 0)
        self.assertIn("wireshark: 4.2.6 -> 4.2.7", result.output)

    @unittest.mock.patch("requests.get", side_effect=mocked_requests_get)
    def test_pr_single_json(self, mock_get):
        result = runner.invoke(
            app,
            [
                "pr",
                "--format",
                "json",
                "--branches",
                "nixos-unstable-small",
                "--branches",
                "nixos-unstable",
                "--branches",
                "nixos-24.11",
                "345583",
            ],
        )
        self.assertEqual(result.exit_code, 0)
        expected = {
            "title": "wireshark: 4.2.6 -> 4.2.7",
            "merged": True,
            "branches": {
                "nixos-unstable-small": True,
                "nixos-unstable": True,
                "nixos-24.11": False,
            },
        }
        output = json.loads(result.output)
        self.assertEqual(output, expected)
