# standard
import json

# third party
import pytest
from typer.testing import CliRunner

# custom
from sunwaee.cli import app


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


@pytest.fixture
def ienv(tmp_path, monkeypatch):
    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


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


def test_init_creates_config_and_workspace(runner, ienv):
    data = _ok(runner.invoke(app, ["init"]))
    assert data["workspace"] == "personal"
    assert (ienv / "config" / "config.toml").exists()
    assert (ienv / "workspaces" / "personal").is_dir()


def test_init_custom_workspace(runner, ienv):
    data = _ok(runner.invoke(app, ["init", "--workspace", "pro"]))
    assert data["workspace"] == "pro"
    assert (ienv / "workspaces" / "pro").is_dir()


def test_init_already_initialised_returns_ok(runner, ienv):
    runner.invoke(app, ["init"])
    data = _ok(runner.invoke(app, ["init"]))
    assert data["workspace"] == "personal"


def test_init_force_reinitialises(runner, ienv):
    runner.invoke(app, ["init"])
    data = _ok(runner.invoke(app, ["init", "--force", "--workspace", "work"]))
    assert data["workspace"] == "work"
    assert (ienv / "workspaces" / "work").is_dir()


def test_init_path_in_response(runner, ienv):
    data = _ok(runner.invoke(app, ["init"]))
    assert "config" in data
    assert "path" in data
