"""Tests for ``tribunal status`` tribunal project status extension."""

from __future__ import annotations

import json
from pathlib import Path


class TestGetAuditSummary:
    def test_empty_when_no_log_file(self, tmp_path: Path):
        from launcher.cli import _get_audit_summary

        result = _get_audit_summary(log_file=tmp_path / "nonexistent.jsonl")
        assert result == {}

    def test_counts_hooks_fired(self, tmp_path: Path):
        from launcher.cli import _get_audit_summary

        log = tmp_path / "audit.jsonl"
        records = [
            {"timestamp": "2025-01-01T00:00:00Z", "outcome": "allowed"},
            {"timestamp": "2025-01-02T00:00:00Z", "outcome": "blocked"},
            {"timestamp": "2025-01-03T00:00:00Z", "outcome": "warned"},
        ]
        log.write_text("\n".join(json.dumps(r) for r in records) + "\n")

        result = _get_audit_summary(log_file=log)
        assert result["hooks_fired"] == 3
        assert result["blocked"] == 1
        assert result["warned"] == 1
        assert result["last_session"] == "2025-01-03"

    def test_handles_malformed_lines(self, tmp_path: Path):
        from launcher.cli import _get_audit_summary

        log = tmp_path / "audit.jsonl"
        log.write_text('{"timestamp":"2025-01-01T00:00:00Z","outcome":"allowed"}\nNOT JSON\n')

        result = _get_audit_summary(log_file=log)
        assert result["hooks_fired"] == 1

    def test_counts_blocked_and_warned_separately(self, tmp_path: Path):
        from launcher.cli import _get_audit_summary

        log = tmp_path / "audit.jsonl"
        entries = [{"outcome": "blocked"}, {"outcome": "blocked"}, {"outcome": "warned"}, {"outcome": "allowed"}]
        log.write_text("\n".join(json.dumps(e) for e in entries) + "\n")

        result = _get_audit_summary(log_file=log)
        assert result["blocked"] == 2
        assert result["warned"] == 1
        assert result["hooks_fired"] == 4


class TestGetTribunalProjectStatus:
    def test_returns_version(self, tmp_path: Path):
        from launcher import __version__
        from launcher.cli import _get_tribunal_project_status

        result = _get_tribunal_project_status(project_dir=tmp_path)
        assert result["version"] == __version__

    def test_no_settings_json(self, tmp_path: Path):
        from launcher.cli import _get_tribunal_project_status

        result = _get_tribunal_project_status(project_dir=tmp_path)
        assert result["claude_settings_ok"] is False
        assert result["claude_settings_note"] == "not found"

    def test_settings_json_present(self, tmp_path: Path):
        from launcher.cli import _get_tribunal_project_status

        (tmp_path / ".claude").mkdir()
        (tmp_path / ".claude" / "settings.json").write_text("{}")
        result = _get_tribunal_project_status(project_dir=tmp_path)
        assert result["claude_settings_ok"] is True

    def test_project_config_loaded(self, tmp_path: Path):
        from launcher.cli import _get_tribunal_project_status

        (tmp_path / ".claude").mkdir()
        cfg = {"language": "Go", "tdd": "strict", "secrets": True, "spec_workflow": True, "context_monitor": True}
        (tmp_path / ".claude" / "tribunal.json").write_text(json.dumps(cfg))

        result = _get_tribunal_project_status(project_dir=tmp_path)
        assert result["project_config"]["language"] == "Go"
        assert result["project_config"]["tdd"] == "strict"

    def test_no_project_config_returns_empty_dict(self, tmp_path: Path):
        from launcher.cli import _get_tribunal_project_status

        result = _get_tribunal_project_status(project_dir=tmp_path)
        assert result["project_config"] == {}


class TestPrintTribunalProjectStatus:
    def test_prints_version(self, capsys):
        from launcher import __version__
        from launcher.cli import _print_tribunal_project_status

        _print_tribunal_project_status({"version": __version__, "claude_settings_ok": True,
                                         "claude_settings_note": "present", "project_config": {},
                                         "hooks_enabled": {}, "audit": {}})
        out = capsys.readouterr().out
        assert __version__ in out

    def test_prints_not_initialised_when_no_config(self, capsys):
        from launcher.cli import _print_tribunal_project_status

        _print_tribunal_project_status({"version": "1.0.0", "claude_settings_ok": False,
                                         "claude_settings_note": "not found", "project_config": {},
                                         "hooks_enabled": {}, "audit": {}})
        out = capsys.readouterr().out
        assert "not initialised" in out

    def test_prints_audit_summary(self, capsys):
        from launcher.cli import _print_tribunal_project_status

        _print_tribunal_project_status({
            "version": "1.0.0",
            "claude_settings_ok": True,
            "claude_settings_note": "present",
            "project_config": {},
            "hooks_enabled": {},
            "audit": {"hooks_fired": 42, "blocked": 3, "warned": 7, "last_session": "2025-01-15"},
        })
        out = capsys.readouterr().out
        assert "42" in out
        assert "3" in out
        assert "2025-01-15" in out

    def test_no_output_for_empty_status(self, capsys):
        from launcher.cli import _print_tribunal_project_status

        _print_tribunal_project_status({})
        out = capsys.readouterr().out
        assert out == ""


class TestStatusCLIParser:
    def test_status_registered(self):
        from launcher.cli import _build_parser

        parser = _build_parser()
        args, _ = parser.parse_known_args(["status"])
        assert args.command == "status"

    def test_status_accepts_json_flag(self):
        from launcher.cli import _build_parser

        parser = _build_parser()
        args, _ = parser.parse_known_args(["status", "--json"])
        assert args.json is True
