"""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)"
	try:
		name = repo.head.shorthand
	except GitError:
		name = _unborn_branch_name(repo)
	return name or "(detached)"


def _unborn_branch_name(repo: Repository) -> str:
	try:
		target = repo.lookup_reference("HEAD").target
	except GitError:
		return "(detached)"
	prefix = "refs/heads/"
	if isinstance(target, str) and target.startswith(prefix):
		return target.removeprefix(prefix)
	return "(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:
		if repo.head_is_unborn:
			repo.set_head(ref_name)
		else:
			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, ""