# standard
# third party
# custom
from ...conftest import ok, err
from sunwaee.cli import app

WS = "personal"
_BASE = ["--workspace", WS]


def _create(runner, title, **kwargs):
    args = ["tasks", "create", "--title", title, *_BASE]
    for k, v in kwargs.items():
        args += [f"--{k.replace('_', '-')}", str(v)]
    return runner.invoke(app, args)


def test_create_basic(runner, ws):
    data = ok(_create(runner, "My Task"))
    assert data["title"] == "My Task"
    assert data["status"] == "todo"
    assert data["priority"] == "medium"
    assert data["workspace"] == WS
    assert "path" in data


def test_create_with_priority(runner, ws):
    data = ok(_create(runner, "High Task", priority="high"))
    assert data["priority"] == "high"


def test_create_with_tags(runner, ws):
    data = ok(_create(runner, "Tagged", tags="a,b"))
    assert data["tags"] == ["a", "b"]


def test_create_with_body(runner, ws):
    data = ok(_create(runner, "Bodied", body="some description"))
    assert data["body"] == "some description"


def test_create_with_due(runner, ws):
    data = ok(_create(runner, "Due Task", due="2026-12-31"))
    assert data["due_date"] == "2026-12-31"


def test_create_with_parent(runner, ws):
    parent = ok(_create(runner, "Parent"))
    child = ok(
        runner.invoke(
            app,
            ["tasks", "create", "--title", "Child", "--parent", "Parent", *_BASE],
        )
    )
    assert child["parent_id"] == parent["id"]


def test_create_parent_not_found(runner, ws):
    e = err(
        runner.invoke(
            app,
            ["tasks", "create", "--title", "Child", "--parent", "ghost", *_BASE],
        )
    )
    assert e["code"] == "NOT_FOUND"


def test_create_uses_default_workspace(runner, ws, monkeypatch):
    monkeypatch.setenv("SUNWAEE_WORKSPACE", WS)
    data = ok(runner.invoke(app, ["tasks", "create", "--title", "Default WS"]))
    assert data["workspace"] == WS


def test_create_writes_file(runner, ws, tmp_path):
    _create(runner, "File Check")
    tasks_dir = tmp_path / "workspaces" / WS / "tasks"
    assert any(tasks_dir.iterdir())
