"""
工具函数
"""

import re
from pathlib import Path
from typing import Tuple


def validate_project_name(name: str) -> Tuple[bool, str]:
    """
    验证项目名称是否符合 Python 包命名规范

    规则：
    - 只能包含小写字母、数字、连字符
    - 必须以字母开头
    - 不能以连字符结尾
    - 长度 1-100 字符

    Args:
        name: 项目名称

    Returns:
        (是否有效, 错误信息)
    """
    if not name:
        return False, "项目名称不能为空"

    if len(name) > 100:
        return False, "项目名称过长（最多 100 字符）"

    if not re.match(r"^[a-z][a-z0-9-]*[a-z0-9]$", name) and name not in [
        chr(i) for i in range(ord("a"), ord("z") + 1)
    ]:
        return (
            False,
            "项目名称只能包含小写字母、数字和连字符，必须以字母开头，不能以连字符结尾",
        )

    # 检查 Python 关键字
    python_keywords = {
        "False",
        "None",
        "True",
        "and",
        "as",
        "assert",
        "async",
        "await",
        "break",
        "class",
        "continue",
        "def",
        "del",
        "elif",
        "else",
        "except",
        "finally",
        "for",
        "from",
        "global",
        "if",
        "import",
        "in",
        "is",
        "lambda",
        "nonlocal",
        "not",
        "or",
        "pass",
        "raise",
        "return",
        "try",
        "while",
        "with",
        "yield",
    }

    if name.replace("-", "_") in python_keywords:
        return False, f"项目名称不能使用 Python 关键字：{name}"

    return True, ""


def create_directory(path: Path) -> None:
    """
    创建目录（包括父目录）

    Args:
        path: 目录路径

    Raises:
        OSError: 创建失败
    """
    path.mkdir(parents=True, exist_ok=False)


def write_file(path: Path, content: str) -> None:
    """
    写入文件（自动创建父目录）

    Args:
        path: 文件路径
        content: 文件内容

    Raises:
        OSError: 写入失败
    """
    # 确保父目录存在
    path.parent.mkdir(parents=True, exist_ok=True)

    # 写入文件
    path.write_text(content, encoding="utf-8")


def normalize_name(name: str) -> str:
    """
    将项目名称标准化为 Python 包名

    示例：
        my-project -> my_project
        my--project -> my_project

    Args:
        name: 项目名称

    Returns:
        标准化后的包名
    """
    return re.sub(r"[-]+", "_", name)
