import json
from pathlib import Path

import pytest

from absolutelyright.cli import app


def run(capsys: pytest.CaptureFixture[str], *argv: str) -> str:
    app(list(argv), result_action="return_value")
    return capsys.readouterr().out


def test_overview_emits_json(
    claude_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    out = run(capsys, "overview", "--claude-dir", str(claude_dir))
    stats = json.loads(out)
    assert stats["prompts"] == 4


def test_prompts_emits_ndjson(
    claude_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    out = run(capsys, "prompts", "--claude-dir", str(claude_dir))
    rows = [json.loads(line) for line in out.splitlines()]
    assert rows == [{"count": 2, "text": "fix the bug in auth"}]


def test_report_is_human_formatted(
    claude_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    out = run(capsys, "report", "--claude-dir", str(claude_dir))
    assert "── overview" in out
    assert "fix the bug in auth" in out


def test_missing_claude_dir_exits_cleanly(tmp_path: Path) -> None:
    with pytest.raises(SystemExit, match="no transcripts"):
        app(["overview", "--claude-dir", str(tmp_path / "nope")])
