"""Shared repository slug utilities.

Centralises _normalize_repo_slug so it is defined in exactly one place.
"""

from __future__ import annotations

import re
from typing import Optional


def _normalize_repo_slug(remote_url: str) -> Optional[str]:
    """Normalise a git remote URL into an ``owner/repo`` slug.

    Supports both SSH (``git@host:owner/repo.git``) and HTTPS URLs.
    Returns *None* when the URL cannot be parsed.
    """
    if not remote_url:
        return None
    remote_url = remote_url.strip()
    if remote_url.startswith("git@"):
        match = re.match(r"git@[^:]+:([^/]+)/(.+?)(\.git)?$", remote_url)
        if match:
            repo = match.group(2)
            if repo.endswith(".git"):
                repo = repo[:-4]
            return f"{match.group(1)}/{repo}".lower()
        return None
    if remote_url.startswith("http://") or remote_url.startswith("https://"):
        from urllib.parse import urlparse
        parsed = urlparse(remote_url)
        parts = parsed.path.strip("/").split("/")
        if len(parts) >= 2:
            repo = parts[1]
            if repo.endswith(".git"):
                repo = repo[:-4]
            return f"{parts[0]}/{repo}".lower()
    return None
