# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.config import get_workspace_dir
from sunwaee.core.audit import append_log
from sunwaee.core.git import ensure_git_repo, ws_commit
from sunwaee.core.logger import get_logger
from sunwaee.core.output import error, success
from ._helpers import _delete_cascade, _find_in_all, _load

_log = get_logger("modules.tasks")


def delete(
    query: str = typer.Argument(..., help="Task id, slug, or title"),
    workspace: Optional[str] = typer.Option(None, "--workspace", "-w"),
) -> None:
    """Delete a task and all its subtasks."""
    found = _find_in_all(query, workspace)
    if found is None:
        error(f"Task not found: {query!r}", "NOT_FOUND")
        return  # pragma: no cover
    ws, directory, path = found
    ws_dir = get_workspace_dir(ws)
    ensure_git_repo(ws_dir)

    task = _load(path)
    append_log(ws, "tasks", "delete", item_id=task.id, item_title=task.title)
    deleted = _delete_cascade(task, path, directory)
    _log.info("Deleted task %r; %d total deleted", task.title, len(deleted))

    diff = ws_commit(ws_dir, f"tasks: delete '{task.title}'")

    success(
        {
            "deleted": [
                {"id": t.id, "title": t.title, "path": str(p)} for t, p in deleted
            ]
        },
        human_fn=lambda: print(diff),
    )
