"""Integration tests for the CLI."""

import subprocess
import os
from pathlib import Path


SAMPLE_MD = """# CLI test

## Echo test

Should print hello.

```bash
echo hello
```

## Math test

Python should compute 2+2.

```bash
python3 -c "print(2+2)"
```
"""


def run_regimen(*args: str, cwd: str | None = None) -> subprocess.CompletedProcess:
    """Run regimen CLI and return result."""
    return subprocess.run(
        ["regimen", *args],
        capture_output=True,
        text=True,
        cwd=cwd,
    )


def test_full_flow(tmp_path):
    """Test start -> step -> step -> status flow."""
    md_file = tmp_path / "test.md"
    md_file.write_text(SAMPLE_MD)

    # Start
    r = run_regimen("start", str(md_file), cwd=str(tmp_path))
    assert r.returncode == 0
    assert "Session:" in r.stdout
    slug = r.stdout.split("Session: ")[1].split("\n")[0].strip()

    # Step 1
    r = run_regimen("step", slug, cwd=str(tmp_path))
    assert r.returncode == 0
    assert "Step 1/2" in r.stdout
    assert "hello" in r.stdout

    # Step 2
    r = run_regimen("step", slug, cwd=str(tmp_path))
    assert r.returncode == 0
    assert "Step 2/2" in r.stdout
    assert "4" in r.stdout

    # Status
    r = run_regimen("status", slug, cwd=str(tmp_path))
    assert r.returncode == 0
    assert "completed" in r.stdout
    assert "[PASS]" in r.stdout

    # Step on completed session
    r = run_regimen("step", slug, cwd=str(tmp_path))
    assert r.returncode == 1


def test_rerun(tmp_path):
    """Test that rerun re-executes the last step."""
    md_file = tmp_path / "test.md"
    md_file.write_text(SAMPLE_MD)

    r = run_regimen("start", str(md_file), cwd=str(tmp_path))
    slug = r.stdout.split("Session: ")[1].split("\n")[0].strip()

    # Step 1
    run_regimen("step", slug, cwd=str(tmp_path))

    # Rerun step 1
    r = run_regimen("rerun", slug, cwd=str(tmp_path))
    assert r.returncode == 0
    assert "run #2" in r.stdout
    assert "Step 1/2" in r.stdout


def test_abort(tmp_path):
    md_file = tmp_path / "test.md"
    md_file.write_text(SAMPLE_MD)

    r = run_regimen("start", str(md_file), cwd=str(tmp_path))
    slug = r.stdout.split("Session: ")[1].split("\n")[0].strip()

    r = run_regimen("abort", slug, cwd=str(tmp_path))
    assert r.returncode == 0
    assert "aborted" in r.stdout


def test_list(tmp_path):
    md_file = tmp_path / "test.md"
    md_file.write_text(SAMPLE_MD)

    run_regimen("start", str(md_file), cwd=str(tmp_path))
    r = run_regimen("list", cwd=str(tmp_path))
    assert r.returncode == 0
    assert "CLI test" in r.stdout


def test_missing_file(tmp_path):
    r = run_regimen("start", "/nonexistent/file.md", cwd=str(tmp_path))
    assert r.returncode == 1


def test_bad_slug(tmp_path):
    r = run_regimen("step", "nonexistent-slug", cwd=str(tmp_path))
    assert r.returncode == 1
