"""
commands/branch.py
------------------
Branch management commands.
  create <branch> → git checkout -b <branch>
  switch <branch> → git checkout <branch>
  delete <branch> → git branch -d <branch>
"""

from vibe.git_wrapper import run_git_command
from vibe.ui import success, error, info


def create(branch: str) -> None:
    """Create and immediately switch to a new branch."""
    if not branch or not branch.strip():
        error("Branch name cannot be empty.")
        return

    ok, out = run_git_command(["checkout", "-b", branch.strip()])
    if not ok:
        error(f"Failed to create branch '{branch}': {out}")
        return

    success(f"Created and switched to branch '{branch}'.")


def switch(branch: str) -> None:
    """Switch to an existing branch."""
    if not branch or not branch.strip():
        error("Branch name cannot be empty.")
        return

    ok, out = run_git_command(["checkout", branch.strip()])
    if not ok:
        error(f"Failed to switch to branch '{branch}': {out}")
        return

    success(f"Switched to branch '{branch}'.")
    info(out)


def delete(branch: str) -> None:
    """
    Delete a branch (safe delete — refuses if unmerged).
    Equivalent to: git branch -d <branch>
    """
    if not branch or not branch.strip():
        error("Branch name cannot be empty.")
        return

    ok, out = run_git_command(["branch", "-d", branch.strip()])
    if not ok:
        error(f"Failed to delete branch '{branch}': {out}")
        return

    success(f"Branch '{branch}' deleted.")


def list_branches() -> None:
    """List all local branches."""
    ok, out = run_git_command(["branch", "-a"])
    if not ok:
        error(f"Failed to list branches: {out}")
        return

    info("Branches:")
    print(out)
