#!/bin/bash

# ANSI 转义序列定义
GREEN='\033[0;32m'
NC='\033[0m'  # 重置颜色

# 查找项目根目录
find_project_root() {
    local current_dir=$(pwd)
    while true; do
        if [[ -f "$current_dir/manage.py" || -d "$current_dir/.git" ]]; then
            echo "$current_dir"
            return
        fi
        local parent_dir=$(dirname "$current_dir")
        if [[ "$parent_dir" == "$current_dir" ]]; then
            echo "$current_dir"
            return
        fi
        current_dir="$parent_dir"
    done
}

# 获取项目名称
get_project_name() {
    local project_root=$(find_project_root)
    basename "$project_root"
}

# 创建虚拟环境
create_venv() {
    local envs_root="/envs"
    local project_name=$(get_project_name)
    local venv_path="$envs_root/$project_name"

    # 创建 envs 目录（带权限设置）
    if [[ ! -d "$envs_root" ]]; then
        sudo mkdir -p "$envs_root"
        sudo chmod 755 "$envs_root"  # 设置合理权限
    fi

    # 安装 virtualenv（使用 pip3 避免 Python2 问题）
    if ! command -v virtualenv &> /dev/null; then
        echo -e "${GREEN}ℹ️ 检测到未安装 virtualenv，正在安装...${NC}"
        if ! sudo pip3 install virtualenv; then
            echo -e "${RED}❌ 安装 virtualenv 失败，请手动安装后重试${NC}"
            exit 1
        fi
    fi

    # 创建虚拟环境并严格校验
    if [[ ! -f "$venv_path/bin/activate" ]]; then
        local python_version="python$(python3 -c 'import sys; print(sys.version_info.major)').$(python3 -c 'import sys; print(sys.version_info.minor)')"
        echo -e "${GREEN}ℹ️ 正在创建虚拟环境...${NC}"
        virtualenv "$venv_path" --python="$python_version"
        
        # 新增：检查虚拟环境是否创建成功
        if [[ ! -f "$venv_path/bin/activate" ]]; then
            echo -e "${RED}❌ 虚拟环境创建失败，激活文件不存在${NC}"
            exit 1
        fi
        echo -e "${GREEN}✅ 虚拟环境已创建: $venv_path${NC}"
    else
        echo -e "${GREEN}✅ 虚拟环境已存在: $venv_path${NC}"
    fi

    # 配置别名和补全规则
    configure_alias "$project_name" "$venv_path"
}

# 配置别名和补全规则
configure_alias() {
    local project_name="$1"
    local venv_path="$2"
    local activate_cmd="source $venv_path/bin/activate"
    local bashrc="$HOME/.bashrc"

    # 添加别名（带去重处理）
    if ! grep -q "alias $project_name=" "$bashrc"; then
        echo -e "\nalias $project_name='$activate_cmd'" >> "$bashrc"
    else
        echo -e "${GREEN}ℹ️ 别名已存在，跳过添加${NC}"
    fi

    # 添加补全规则（带去重处理）
    local completion_rule="complete -F _venv_complete $project_name"
    if ! grep -q "$completion_rule" "$bashrc"; then
        echo -e "\n# 虚拟环境补全 - $project_name" >> "$bashrc"
        echo "_venv_complete() {" >> "$bashrc"
        echo "    local cur=\${COMP_WORDS[COMP_CWORD]}" >> "$bashrc"
        echo "    COMPREPLY=( \$(compgen -W \"\$(ls /envs | grep -E '^[a-zA-Z0-9_-]+$')\" -- \$cur) )" >> "$bashrc"
        echo "}" >> "$bashrc"
        echo "$completion_rule" >> "$bashrc"
    else
        echo -e "${GREEN}ℹ️ 补全规则已存在，跳过添加${NC}"
    fi

    # 重新加载 .bashrc
    source "$bashrc"
    echo -e "${GREEN}✅ 别名已设置: $project_name${NC}"
    echo "使用方法: $project_name （输入首字母按 Tab 补全）"
    echo -e "${GREEN}当前虚拟环境路径: $venv_path${NC}"
}

# 主执行逻辑
create_venv
project_name=$(get_project_name)
echo -e "\n🎉 所有操作完成，立即生效："
echo "  激活环境: $project_name"
echo "  Tab 补全: 输入 '${project_name:0:1}' 后按 Tab 查看所有别名"