import subprocess
from pathlib import Path
from typing import Optional


def get_git_config(key: str) -> str:
    """从 Git 全局配置中获取指定项的值"""
    try:
        result = subprocess.run(
            ['git', 'config', '--global', key],
            capture_output=True,
            text=True,
            check=False
        )
        if result.returncode == 0:
            return result.stdout.strip()
    except FileNotFoundError:
        pass
    return ''


def get_git_version(project_dir: Path) -> Optional[str]:
    """获取最近 Git 标签作为版本号（去除前缀 v）"""
    try:
        result = subprocess.run(
            ['git', 'describe', '--tags', '--abbrev=0'],
            cwd=project_dir,
            capture_output=True,
            text=True,
            check=True
        )
        tag = result.stdout.strip().lstrip('v')
        return tag
    except (subprocess.CalledProcessError, FileNotFoundError):
        return None


def get_previous_git_tag(project_dir: Path) -> Optional[str]:
    """获取上一个 Git 标签（用于生成 changelog）"""
    try:
        # 获取所有标签按版本排序，取倒数第二个
        result = subprocess.run(
            ['git', 'tag', '--sort=-v:refname'],
            cwd=project_dir,
            capture_output=True,
            text=True,
            check=True
        )
        tags = result.stdout.strip().splitlines()
        if len(tags) >= 2:
            return tags[1].lstrip('v')
        elif len(tags) == 1:
            return tags[0].lstrip('v')
        return None
    except (subprocess.CalledProcessError, FileNotFoundError):
        return None