# standard
from typing import Optional

# third party
import typer

# custom
from sunwaee.modules.tasks.model import Task, TaskPriority
from sunwaee.config import get_workspace_dir, is_machine_caller
from sunwaee.core.audit import append_log
from sunwaee.core.editor import open_editor
from sunwaee.core.fs import find_md
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 _enrich, _load, _resolve_dir, _save

_log = get_logger("modules.tasks")


def create(
    title: str = typer.Option(..., "--title", "-t", help="Task title"),
    priority: TaskPriority = typer.Option(TaskPriority.MEDIUM, "--priority", "-p"),
    due: Optional[str] = typer.Option(None, "--due", help="Due date (YYYY-MM-DD)"),
    tags: Optional[str] = typer.Option(None, "--tags", help="Comma-separated tags"),
    body: Optional[str] = typer.Option(None, "--body", "-b", help="Task description"),
    parent: Optional[str] = typer.Option(
        None, "--parent", help="Parent task id, slug, or title"
    ),
    workspace: Optional[str] = typer.Option(None, "--workspace", "-w"),
) -> None:
    """Create a new task. Opens $EDITOR if --body is not provided."""
    ws, directory = _resolve_dir(workspace)
    ws_dir = get_workspace_dir(ws)
    ensure_git_repo(ws_dir)

    tag_list = [t.strip() for t in tags.split(",")] if tags else []

    parent_id = None
    if parent:
        parent_path = find_md(parent, directory)
        if parent_path is None:
            error(f"Parent task not found: {parent!r}", "NOT_FOUND")
            return  # pragma: no cover
        parent_id = _load(parent_path).id

    if body is None and not is_machine_caller():  # pragma: no cover
        body = open_editor()

    task = Task(
        title=title,
        priority=priority,
        due_date=due,
        parent_id=parent_id,
        tags=tag_list,
        body=body or "",
    )
    path = _save(task, directory)
    diff = ws_commit(ws_dir, f"tasks: create '{task.title}'")
    _log.info("Created task %r at %s", title, path)
    append_log(ws, "tasks", "create", item_id=task.id, item_title=task.title)

    success(_enrich(task, ws, path), human_fn=lambda: print(diff))
