"""Shared git helpers used across CLI commands."""

import hashlib
import json
import os
import subprocess
from pathlib import Path

import click


def get_repo_root() -> Path:
    """Find git repository root from current directory."""
    cwd = Path.cwd()
    for parent in [cwd, *cwd.parents]:
        if (parent / ".git").exists():
            return parent
    raise click.ClickException("Not in a git repository")


def get_staged_diff_hash() -> str:
    """Get SHA-256 hash of staged changes."""
    result = subprocess.run(
        ["git", "diff", "--staged"],
        capture_output=True,
        text=True,
    )
    return hashlib.sha256(result.stdout.encode()).hexdigest()


def get_git_user_name() -> str:
    """Get git user.name, falling back to 'unknown'."""
    result = subprocess.run(
        ["git", "config", "user.name"],
        capture_output=True,
        text=True,
    )
    return result.stdout.strip() or "unknown"


def resolve_local_api_key(repo_root: Path) -> tuple[str | None, str | None]:
    """Resolve API key and URL from project-local sources.

    Checks project-local config only (not global config or GJALLA_API_KEY env var,
    which are already handled by Settings.load()). Use this to layer local sources
    on top of Settings.

    Priority order:
    1. Local .gjalla/config.json api_key_env (env var reference)

    Returns:
        (api_key, api_url) — either or both may be None.
    """
    local_config_path = repo_root / ".gjalla" / "config.json"
    if not local_config_path.exists():
        return None, None

    try:
        local_config = json.loads(local_config_path.read_text())
    except (json.JSONDecodeError, OSError):
        return None, None

    api_url = local_config.get("api_url")
    env_var_name = local_config.get("api_key_env", "")
    if env_var_name:
        key = os.environ.get(env_var_name)
        if key:
            return key, api_url

    return None, api_url
