"""Local branch listing and checkout for the pgt TUI."""

from __future__ import annotations

from pygit2 import Commit, GitError, Repository, reference_is_valid_name


def current_branch_name(repo: Repository) -> str:
	if repo.head_is_detached:
		return "(detached)"
	return repo.head.shorthand or "(detached)"


def list_local_branches(repo: Repository) -> list[str]:
	return sorted(repo.branches.local)


def checkout_branch(repo: Repository, branch: str) -> tuple[bool, str]:
	try:
		repo.checkout(f"refs/heads/{branch}")
	except (GitError, KeyError) as exc:
		message = str(exc).strip()
		return False, message or "Checkout failed"
	return True, ""


def create_branch_from_current(repo: Repository, name: str) -> tuple[bool, str]:
	branch = name.strip()
	if not branch:
		return False, "Branch name is empty"
	ref_name = f"refs/heads/{branch}"
	if not reference_is_valid_name(ref_name):
		return False, f"Invalid branch name: {branch}"
	if branch in repo.branches.local:
		return False, f"Branch already exists: {branch}"
	try:
		commit = repo.head.peel(Commit)
		repo.branches.create(branch, commit)
		repo.checkout(ref_name)
	except GitError as exc:
		message = str(exc).strip()
		return False, message or "Failed to create branch"
	return True, ""