# standard
import json
import pytest

# third party
from typer.testing import CliRunner

# custom
from sunwaee.cli import app


@pytest.fixture
def runner():
    return CliRunner()


@pytest.fixture
def env(tmp_path, monkeypatch):
    """Isolated environment: temp config + workspaces dirs, machine caller."""
    monkeypatch.setenv("SUNWAEE_CONFIG_DIR", str(tmp_path / "config"))
    monkeypatch.setenv("SUNWAEE_WORKSPACES_DIR", str(tmp_path / "workspaces"))
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    monkeypatch.delenv("SUNWAEE_WORKSPACE", raising=False)
    return tmp_path


@pytest.fixture
def ws(runner, env):
    """Isolated env with a 'personal' workspace already created."""
    result = runner.invoke(app, ["workspaces", "create", "personal"])
    assert result.exit_code == 0
    return env


def ok(result) -> dict:
    """Assert exit 0 and return parsed JSON data."""
    assert result.exit_code == 0, result.output
    payload = json.loads(result.output)
    assert payload["ok"] is True
    return payload["data"]


def err(result) -> dict:
    """Assert exit non-zero and return parsed JSON error."""
    assert result.exit_code != 0, result.output
    payload = json.loads(result.output)
    assert payload["ok"] is False
    return payload
