#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git 自动上传脚本（跨平台）
支持 Windows、Linux、Mac
"""

import os
import sys
import subprocess
import platform
from datetime import datetime

# 颜色输出（Windows 10+ 支持 ANSI）
def print_color(text, color="white"):
    colors = {
        "red": "\033[0;31m",
        "green": "\033[0;32m",
        "yellow": "\033[1;33m",
        "blue": "\033[0;34m",
        "reset": "\033[0m"
    }
    if platform.system() == "Windows":
        # Windows 10+ 支持 ANSI，需要启用
        try:
            import ctypes
            kernel32 = ctypes.windll.kernel32
            kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
        except:
            pass
    
    color_code = colors.get(color.lower(), colors["reset"])
    reset = colors["reset"]
    print(f"{color_code}{text}{reset}")

def run_command(cmd, check=True):
    """执行命令并返回结果"""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            check=check,
            capture_output=True,
            text=True,
            encoding='utf-8'
        )
        return result.returncode == 0, result.stdout.strip(), result.stderr.strip()
    except subprocess.CalledProcessError as e:
        return False, e.stdout.strip() if hasattr(e, 'stdout') else "", e.stderr.strip() if hasattr(e, 'stderr') else ""

def main():
    print_color("=== Git 自动上传脚本 ===", "green")
    
    # 检查是否在 git 仓库中
    if not os.path.exists(".git"):
        print_color("错误: 当前目录不是 git 仓库", "red")
        sys.exit(1)
    
    # 获取当前分支
    success, branch, _ = run_command("git branch --show-current", check=False)
    if not success:
        success, branch, _ = run_command("git rev-parse --abbrev-ref HEAD", check=False)
    
    if not branch:
        print_color("错误: 无法获取当前分支", "red")
        sys.exit(1)
    
    print_color(f"当前分支: {branch}", "yellow")
    
    # 检查是否有未提交的更改
    success, status, _ = run_command("git status --porcelain", check=False)
    if not status:
        print_color("没有需要提交的更改", "yellow")
        response = input("是否继续检查远程更新? (y/n) ").strip().lower()
        if response == 'y':
            print_color("拉取远程更新...", "green")
            run_command(f"git pull origin {branch}", check=False)
        sys.exit(0)
    
    # 显示当前状态
    print_color("当前更改状态:", "yellow")
    success, status_output, _ = run_command("git status --short", check=False)
    print(status_output)
    
    # 询问是否继续
    response = input("是否继续提交并推送? (y/n) ").strip().lower()
    if response != 'y':
        print_color("操作已取消", "yellow")
        sys.exit(0)
    
    # 获取提交信息
    if len(sys.argv) > 1:
        commit_msg = " ".join(sys.argv[1:])
    else:
        default_msg = f"chore: update code {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        user_msg = input(f"请输入提交信息（或直接按回车使用默认信息）: ").strip()
        commit_msg = user_msg if user_msg else default_msg
    
    # 添加所有更改
    print_color("添加文件到暂存区...", "green")
    success, _, error = run_command("git add -A")
    if not success:
        print_color(f"添加文件失败: {error}", "red")
        sys.exit(1)
    
    # 提交更改
    print_color("提交更改...", "green")
    success, _, error = run_command(f'git commit -m "{commit_msg}"')
    if not success:
        if "nothing to commit" in error.lower():
            print_color("没有需要提交的更改", "yellow")
            sys.exit(0)
        print_color(f"提交失败: {error}", "red")
        sys.exit(1)
    print_color("提交成功!", "green")
    
    # 推送到远程
    print_color("推送到远程仓库...", "green")
    success, _, error = run_command(f"git push origin {branch}")
    if not success:
        print_color(f"推送失败: {error}", "red")
        print_color(f"提示: 可以手动执行 'git push origin {branch}'", "yellow")
        print_color("可能需要设置远程仓库地址或进行身份验证", "yellow")
        sys.exit(1)
    
    print_color("✓ 推送成功!", "green")
    print_color("=== 完成 ===", "green")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print_color("\n操作已取消", "yellow")
        sys.exit(0)
    except Exception as e:
        print_color(f"发生错误: {e}", "red")
        sys.exit(1)

