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

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


def _create_note_and_get_log_id(runner, ws) -> str:
    """Create a note and return the log entry id for that creation."""
    runner.invoke(
        app,
        ["notes", "create", "--title", "Read target", "--body", "x", "--workspace", WS],
    )
    data = ok(runner.invoke(app, ["logs", "list", "--module", "notes", "--operation", "create", *_BASE]))
    entry = next(e for e in data if e.get("item_title") == "Read target")
    return entry["id"]


### READ COMMAND


def test_log_read_by_full_id(runner, ws):
    log_id = _create_note_and_get_log_id(runner, ws)
    data = ok(runner.invoke(app, ["logs", "read", log_id, *_BASE]))
    assert data["id"] == log_id
    assert data["module"] == "notes"
    assert data["operation"] == "create"


def test_log_read_by_id_prefix(runner, ws):
    log_id = _create_note_and_get_log_id(runner, ws)
    prefix = log_id[:8]
    data = ok(runner.invoke(app, ["logs", "read", prefix, *_BASE]))
    assert data["id"] == log_id


def test_log_read_entry_has_all_fields(runner, ws):
    log_id = _create_note_and_get_log_id(runner, ws)
    data = ok(runner.invoke(app, ["logs", "read", log_id, *_BASE]))
    assert "id" in data
    assert "timestamp" in data
    assert "caller" in data
    assert "workspace" in data
    assert "module" in data
    assert "operation" in data
    assert "ok" in data


def test_log_read_not_found(runner, ws):
    e = err(runner.invoke(app, ["logs", "read", "zzz-no-such-id", *_BASE]))
    assert e["code"] == "NOT_FOUND"


def test_log_read_all_workspaces(runner, ws):
    """Read without --workspace searches across all workspaces."""
    log_id = _create_note_and_get_log_id(runner, ws)
    data = ok(runner.invoke(app, ["logs", "read", log_id]))
    assert data["id"] == log_id


def test_log_read_returns_item_title(runner, ws):
    log_id = _create_note_and_get_log_id(runner, ws)
    data = ok(runner.invoke(app, ["logs", "read", log_id, *_BASE]))
    assert data["item_title"] == "Read target"


def test_log_read_entry_id_is_uuid(runner, ws):
    log_id = _create_note_and_get_log_id(runner, ws)
    # UUIDs are 36 chars: 8-4-4-4-12
    assert len(log_id) == 36
    assert log_id.count("-") == 4
