"""
Validation: pathname, ref format, project; repo discovery via pygit2.
Ported from gitweb/gitweb.perl (is_valid_pathname, is_valid_ref_format,
is_valid_project). Repo check uses pygit2.discover_repository.
"""

from __future__ import annotations

import os
import re
from collections.abc import Callable

import pygit2


def is_valid_pathname(input_path: str | None) -> bool:
    """No '.', '..' as path elements, no null, no doubled slashes. Port of is_valid_pathname."""
    if input_path is None:
        return False
    if "\0" in input_path:
        return False
    parts = input_path.strip("/").split("/")
    return all(p not in ("", ".", "..") for p in parts)


def is_valid_ref_format(input_ref: str | None) -> bool:
    """Git-check-ref-format rules: no /., no .., no control/space/special at start/end. Port of is_valid_ref_format."""
    if input_ref is None:
        return False
    if "/." in input_ref or input_ref.startswith(".") or ".." in input_ref:
        return False
    if input_ref.endswith("/") or input_ref.endswith(".lock"):
        return False
    # No ASCII control, space, ~^:?*[
    return not re.search(r"[\x00-\x20\x7f ~^:?*\[\]]", input_ref)


def check_export_ok(
    git_dir: str,
    export_ok: str = "",
    export_auth_hook: Callable[[str], bool] | None = None,
    across_fs: bool = False,
) -> bool:
    """True if path is a git repo (via pygit2.discover_repository) and optional export_ok file / auth hook pass."""
    if not os.path.isdir(git_dir):
        return False
    try:
        discovered = pygit2.discover_repository(git_dir, across_fs)
        if not discovered:
            return False
    except (KeyError, pygit2.GitError, OSError):
        return False
    if export_ok and not os.path.isfile(os.path.join(git_dir, export_ok)):
        return False
    return not export_auth_hook or export_auth_hook(git_dir)


def is_valid_project(
    project: str | None,
    projectroot: str,
    export_ok: str,
    strict_export: bool,
    project_in_list: Callable[[str], bool],
) -> bool:
    """Pathname valid, dir exists, export_ok, and (if strict) in project list. Port of is_valid_project."""
    if project is None:
        return False
    if not is_valid_pathname(project):
        return False
    full = os.path.join(projectroot, project)
    if not os.path.isdir(full):
        return False
    if not check_export_ok(full, export_ok):
        return False
    return not strict_export or project_in_list(project)