"""Tests for pulse CLI module."""

import json
import os
import time

import pytest

from pulse.cli import cmd_init, format_results, main
from pulse.checker import CheckResult, VitalResult


class TestFormatResults:
    def test_all_ok(self):
        results = [VitalResult("Svc", [CheckResult("a", True, "ok", 60.0)])]
        output = format_results(results)
        assert "OK" in output
        assert "Svc" in output

    def test_warn(self):
        results = [VitalResult("Svc", [
            CheckResult("a", True, "ok"),
            CheckResult("b", False, "fail"),
        ])]
        output = format_results(results)
        assert "WARN" in output
        assert "\u2717" in output  # cross mark
        assert "\u2713" in output  # check mark

    def test_crit(self):
        results = [VitalResult("Svc", [
            CheckResult("a", False, "fail1"),
            CheckResult("b", False, "fail2"),
        ])]
        output = format_results(results)
        assert "CRIT" in output


class TestCLI:
    def test_init_yaml(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        ret = main(["init"])
        assert ret == 0
        assert (tmp_path / "pulse.yaml").exists()

    def test_init_json(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        ret = main(["init", "--json"])
        assert ret == 0
        assert (tmp_path / "pulse.json").exists()
        # Validate it's proper JSON
        data = json.loads((tmp_path / "pulse.json").read_text())
        assert "vitals" in data

    def test_init_no_overwrite(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        (tmp_path / "pulse.yaml").write_text("existing")
        ret = main(["init"])
        assert ret == 1

    def test_init_force(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        (tmp_path / "pulse.yaml").write_text("existing")
        ret = main(["init", "--force"])
        assert ret == 0

    def test_check_no_config(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        ret = main(["check"])
        assert ret == 2

    def test_check_healthy(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        (tmp_path / "data.json").write_text("{}")
        config = {
            "vitals": [{
                "name": "Test",
                "checks": [{"type": "file_freshness", "path": "data.json", "max_age": "1h"}],
            }]
        }
        (tmp_path / "pulse.json").write_text(json.dumps(config))
        ret = main(["check"])
        assert ret == 0

    def test_check_json_output(self, tmp_path, monkeypatch, capsys):
        monkeypatch.chdir(tmp_path)
        (tmp_path / "data.json").write_text("{}")
        config = {
            "vitals": [{
                "name": "Test",
                "checks": [{"type": "file_freshness", "path": "data.json", "max_age": "1h"}],
            }]
        }
        (tmp_path / "pulse.json").write_text(json.dumps(config))
        ret = main(["check", "--json"])
        assert ret == 0
        captured = capsys.readouterr()
        data = json.loads(captured.out)
        assert data["healthy"] is True

    def test_version(self, capsys):
        with pytest.raises(SystemExit) as exc:
            main(["--version"])
        assert exc.value.code == 0

    def test_no_command(self, capsys):
        ret = main([])
        assert ret == 0  # prints help

    def test_history_no_data(self, tmp_path, monkeypatch):
        monkeypatch.chdir(tmp_path)
        ret = main(["history"])
        assert ret == 0
