"""GitHub repository utilities."""

import logging
import re
from pathlib import Path
from typing import Optional

from git import Repo
from git.exc import GitCommandError

logger = logging.getLogger(__name__)


def is_github_url(target: str) -> bool:
    """Check if target is a GitHub URL."""
    pattern = r"^https?://github\.com/[\w-]+/[\w.-]+/?$"
    return bool(re.match(pattern, target))


def extract_repo_name(url: str) -> str:
    """Extract repository name from GitHub URL."""
    match = re.search(r"github\.com/([\w-]+)/([\w.-]+)", url)
    if match:
        return f"{match.group(1)}_{match.group(2)}"
    return "unknown_repo"


def clone_repository(url: str, dest_dir: Path) -> Optional[Path]:
    """Clone a GitHub repository."""
    repo_name = extract_repo_name(url)
    repo_path = dest_dir / repo_name
    
    if repo_path.exists():
        logger.info(f"Repository already exists at {repo_path}")
        return repo_path
    
    try:
        logger.info(f"Cloning repository: {url}")
        Repo.clone_from(url, repo_path)
        logger.info(f"Successfully cloned to {repo_path}")
        return repo_path
    except GitCommandError as e:
        logger.error(f"Failed to clone repository: {e}")
        return None
