import shlex
import subprocess
import uuid

from onako.tmux_orchestrator import TmuxOrchestrator


def create_task(
    orch: TmuxOrchestrator,
    prompt: str,
    working_dir: str | None = None,
    skip_permissions: bool = False,
    branch: str | None = None,
    base_branch: str | None = None,
    worktree_manager=None,
) -> dict:
    """Create a new Claude Code task in a tmux window.

    Shared by the API endpoint and CLI command.
    """
    claude_session_id = str(uuid.uuid4())
    if skip_permissions:
        command = f"claude --dangerously-skip-permissions --session-id {claude_session_id} {shlex.quote(prompt)}"
    else:
        command = f"claude --session-id {claude_session_id} {shlex.quote(prompt)}"

    worktree_path = None
    if branch and worktree_manager:
        base = base_branch or "main"
        wt_path = worktree_manager.ensure_worktree(branch, base)
        working_dir = str(wt_path)
        worktree_path = str(wt_path)

    return orch.create_task(
        command=command,
        working_dir=working_dir,
        prompt=prompt,
        claude_session_id=claude_session_id,
        branch=branch if worktree_manager else None,
        worktree_path=worktree_path,
    )
