import json
from pathlib import Path
from typer.testing import CliRunner
from granule.cli import app

runner = CliRunner()

def test_full_cli_pipeline(tmp_path: Path):
    # ingest
    doc_path = tmp_path / "doc.json"
    r1 = runner.invoke(app, ["ingest", "Some input article text.", "--kind", "blog", "-o", str(doc_path)])
    assert r1.exit_code == 0, r1.output
    data = json.loads(doc_path.read_text(encoding="utf-8"))
    assert "text" in data
    # dissect
    atoms_path = tmp_path / "atoms.json"
    r2 = runner.invoke(app, ["dissect", str(doc_path), "--max-tokens", "50", "-o", str(atoms_path)])
    assert r2.exit_code == 0, r2.output
    atoms_data = json.loads(atoms_path.read_text(encoding="utf-8"))
    assert "atoms" in atoms_data and isinstance(atoms_data["atoms"], list)
    # expand
    unit_path = tmp_path / "unit.json"
    r3 = runner.invoke(app, ["expand", str(atoms_path), "--target", "30s", "-o", str(unit_path)])
    assert r3.exit_code == 0, r3.output
    unit_data = json.loads(unit_path.read_text(encoding="utf-8"))
    assert unit_data  # minimal shape
    # stream
    session_path = tmp_path / "session.jsonl"
    r4 = runner.invoke(app, ["stream", str(atoms_path), "--pace", "10s", "--until", "20s", "-o", str(session_path)])
    assert r4.exit_code == 0, r4.output
    lines = session_path.read_text(encoding="utf-8").strip().splitlines()
    assert 1 <= len(lines) <= 3
