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

import os
import re
from typing import Callable

import pygit2

# OID regex: 40 hex (SHA-1) or 40+24 (SHA-256). Port of $oid_regex / oid_nlen_regex.
OID_PATTERN = re.compile(r"^[0-9a-fA-F]{7,64}$")
SHA1_LEN = 40
SHA256_EXTRA = 24


def oid_nlen_regex(length: int | str) -> re.Pattern[str]:
    """Regex matching exactly `length` hex chars. Port of oid_nlen_regex."""
    if isinstance(length, str) and "-" in length:
        lo, hi = length.split("-")
        return re.compile(f"^[0-9a-fA-F]{{{int(lo)},{int(hi)}}}$")
    n = int(length)
    return re.compile(f"^[0-9a-fA-F]{{{n}}}$")


def oid_nlen_prefix_infix_regex(nlen: int, prefix: str, infix: str) -> re.Pattern[str]:
    """Two OID-like groups with literal prefix and infix. Port of oid_nlen_prefix_infix_regex."""
    rx = oid_nlen_regex(nlen)
    return re.compile(f"^{re.escape(prefix)}{rx.pattern}{re.escape(infix)}{rx.pattern}$")


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("/")
    for p in parts:
        if p in ("", ".", ".."):
            return False
    return True


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, ~^:?*[
    if re.search(r"[\x00-\x20\x7f ~^:?*\[\]]", input_ref):
        return False
    return True


def is_valid_refname(input_ref: str | None) -> bool:
    """Either full OID hex or valid pathname + ref format. Port of is_valid_refname."""
    if input_ref is None:
        return False
    if OID_PATTERN.match(input_ref):
        return True
    return is_valid_pathname(input_ref) and is_valid_ref_format(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
    if export_auth_hook is not None and not export_auth_hook(git_dir):
        return False
    return True


def is_valid_action(action: str | None, allowed_actions: set[str]) -> bool:
    """Action is in allowed set. Port of is_valid_action."""
    return action in allowed_actions if action else False


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
    if strict_export and not project_in_list(project):
        return False
    return True