"""Resolve a display label for the current repository."""

from __future__ import annotations

from pathlib import Path

from pygittools.tui.pygitweb_layout import load_pygitweb_layout


def repo_project_label(repo_path: Path) -> str:
    """Return the PyGitWeb project path when under PROJECTROOT, else the worktree path."""
    worktree = _worktree_path(repo_path)
    try:
        layout = load_pygitweb_layout()
    except OSError:
        return str(worktree)
    projectroot = layout.projectroot.resolve()
    try:
        relative = worktree.relative_to(projectroot)
    except ValueError as e:
        print(e)
        return str(worktree)
    return str(relative).replace("\\", "/")


def _worktree_path(repo_path: Path) -> Path:
    resolved = repo_path.resolve()
    if resolved.name == ".git":
        return resolved.parent
    return resolved