# TSP智能助手 - 自动推送脚本 (PowerShell版本)
# 使用方法: .\auto_push.ps1 [提交信息]

param(
    [string]$CommitMessage = "",
    [switch]$Force = $false,
    [switch]$NoConfirm = $false
)

# 设置控制台编码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

function Write-Step {
    param(
        [int]$Step,
        [int]$Total,
        [string]$Message
    )
    Write-ColorOutput "[$Step/$Total] $Message" "Cyan"
}

function Show-GitStatus {
    Write-ColorOutput "`n📋 当前Git状态:" "Yellow"
    $status = git status --porcelain
    if ($status) {
        $status | ForEach-Object {
            $line = $_
            if ($line.StartsWith("??")) {
                Write-ColorOutput "  + $($line.Substring(3))" "Green"
            } elseif ($line.StartsWith(" M")) {
                Write-ColorOutput "  ~ $($line.Substring(3))" "Yellow"
            } elseif ($line.StartsWith(" D")) {
                Write-ColorOutput "  - $($line.Substring(3))" "Red"
            } else {
                Write-ColorOutput "  $line" "White"
            }
        }
    } else {
        Write-ColorOutput "  工作区干净，无更改" "Green"
    }
}

function Get-CommitMessage {
    if ($CommitMessage) {
        return $CommitMessage
    }
    
    # 尝试从最近提交生成智能消息
    $lastCommit = git log --oneline -1 2>$null
    if ($lastCommit) {
        $suggested = "feat: 自动提交更新 - $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
    } else {
        $suggested = "feat: 初始提交 - $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
    }
    
    Write-ColorOutput "`n💡 建议的提交信息: $suggested" "Cyan"
    $custom = Read-Host "请输入自定义提交信息 (直接回车使用建议)"
    
    if ($custom) {
        return $custom
    } else {
        return $suggested
    }
}

function Test-GitRepository {
    try {
        git status --porcelain >$null 2>&1
        return $LASTEXITCODE -eq 0
    } catch {
        return $false
    }
}

function Show-CommitStats {
    Write-ColorOutput "`n📊 提交统计:" "Yellow"
    $commitHash = git log --oneline -1 | Select-String -Pattern "^\w+" | ForEach-Object { $_.Matches[0].Value }
    $filesChanged = git diff --cached --numstat | Measure-Object | Select-Object -ExpandProperty Count
    $insertions = git diff --cached --numstat | ForEach-Object { 
        $parts = $_ -split '\s+'
        if ($parts[0] -match '^\d+$') { [int]$parts[0] } else { 0 }
    } | Measure-Object -Sum | Select-Object -ExpandProperty Sum
    $deletions = git diff --cached --numstat | ForEach-Object { 
        $parts = $_ -split '\s+'
        if ($parts[1] -match '^\d+$') { [int]$parts[1] } else { 0 }
    } | Measure-Object -Sum | Select-Object -ExpandProperty Sum
    
    Write-ColorOutput "  提交哈希: $commitHash" "White"
    Write-ColorOutput "  文件变更: $filesChanged 个文件" "White"
    Write-ColorOutput "  新增行数: $insertions 行" "Green"
    Write-ColorOutput "  删除行数: $deletions 行" "Red"
    Write-ColorOutput "  净增加: $($insertions - $deletions) 行" "Cyan"
}

# 主程序开始
Write-ColorOutput "========================================" "Magenta"
Write-ColorOutput "TSP智能助手 - 自动推送脚本 v2.0" "Magenta"
Write-ColorOutput "========================================" "Magenta"

# 检查Git仓库
Write-Step 1 4 "检查Git仓库状态"
if (-not (Test-GitRepository)) {
    Write-ColorOutput "❌ Git未初始化或不在Git仓库中" "Red"
    Write-ColorOutput "请确保在正确的Git仓库目录中运行此脚本" "Yellow"
    Read-Host "按任意键退出"
    exit 1
}
Write-ColorOutput "✅ Git仓库状态正常" "Green"

# 显示状态
Show-GitStatus

# 检查是否有更改
$hasChanges = git status --porcelain | Measure-Object | Select-Object -ExpandProperty Count
if ($hasChanges -eq 0) {
    Write-ColorOutput "`n✅ 工作区干净，无需提交" "Green"
    Read-Host "按任意键退出"
    exit 0
}

# 显示详细状态
Write-ColorOutput "`n📊 详细状态信息:" "Yellow"

# 检查未暂存的更改
$unstaged = git diff --name-only 2>$null
if ($unstaged) {
    Write-ColorOutput "  未暂存更改: $($unstaged.Count) 个文件" "Yellow"
    $unstaged | ForEach-Object { Write-ColorOutput "    ~ $_" "Yellow" }
} else {
    Write-ColorOutput "  未暂存更改: 无" "Green"
}

# 检查已暂存的更改
$staged = git diff --cached --name-only 2>$null
if ($staged) {
    Write-ColorOutput "  已暂存更改: $($staged.Count) 个文件" "Green"
    $staged | ForEach-Object { Write-ColorOutput "    + $_" "Green" }
} else {
    Write-ColorOutput "  已暂存更改: 无" "Green"
}

# 检查未跟踪的文件
$untracked = git ls-files --others --exclude-standard 2>$null
if ($untracked) {
    Write-ColorOutput "  未跟踪文件: $($untracked.Count) 个文件" "Cyan"
    $untracked | ForEach-Object { Write-ColorOutput "    + $_" "Cyan" }
} else {
    Write-ColorOutput "  未跟踪文件: 无" "Green"
}

# 确认操作
if (-not $NoConfirm) {
    Write-ColorOutput "`n❓ 是否继续推送?" "Yellow"
    $confirm = Read-Host "输入 'y' 继续，其他键取消"
    if ($confirm -ne 'y') {
        Write-ColorOutput "操作已取消" "Yellow"
        Read-Host "按任意键退出"
        exit 0
    }
}

# 添加文件
Write-Step 2 4 "添加所有更改到暂存区"
try {
    git add .
    Write-ColorOutput "✅ 文件已添加到暂存区" "Green"
} catch {
    Write-ColorOutput "❌ 添加文件失败: $($_.Exception.Message)" "Red"
    Read-Host "按任意键退出"
    exit 1
}

# 生成提交信息
Write-Step 3 4 "生成提交信息"
$finalCommitMessage = Get-CommitMessage
Write-ColorOutput "提交信息: $finalCommitMessage" "Cyan"

# 提交更改
try {
    git commit -m $finalCommitMessage
    Write-ColorOutput "✅ 提交成功" "Green"
} catch {
    Write-ColorOutput "❌ 提交失败: $($_.Exception.Message)" "Red"
    Read-Host "按任意键退出"
    exit 1
}

# 推送到远程
Write-Step 4 4 "推送到远程仓库"

# 先尝试拉取最新更改
Write-ColorOutput "🔄 检查远程更新..." "Cyan"
try {
    git fetch origin main
    Write-ColorOutput "✅ 远程更新检查完成" "Green"
} catch {
    Write-ColorOutput "⚠️ 无法获取远程更新，继续推送..." "Yellow"
}

# 推送到远程
try {
    git push origin main
    Write-ColorOutput "✅ 推送成功" "Green"
} catch {
    Write-ColorOutput "❌ 推送失败: $($_.Exception.Message)" "Red"
    Write-ColorOutput "`n💡 可能的原因:" "Yellow"
    Write-ColorOutput "   - 网络连接问题" "White"
    Write-ColorOutput "   - 远程仓库权限不足" "White"
    Write-ColorOutput "   - 分支冲突" "White"
    Write-ColorOutput "   - 需要先拉取远程更改" "White"
    
    Write-ColorOutput "`n🔧 尝试自动解决冲突..." "Cyan"
    try {
        git pull origin main --rebase
        if ($LASTEXITCODE -eq 0) {
            Write-ColorOutput "✅ 冲突已解决，重新推送..." "Green"
            git push origin main
            if ($LASTEXITCODE -eq 0) {
                Write-ColorOutput "✅ 推送成功！" "Green"
            } else {
                Write-ColorOutput "❌ 重新推送失败" "Red"
                Write-ColorOutput "`n🔧 建议手动解决:" "Yellow"
                Write-ColorOutput "   1. 运行: git pull origin main" "White"
                Write-ColorOutput "   2. 解决冲突后运行: git push origin main" "White"
                Read-Host "按任意键退出"
                exit 1
            }
        } else {
            Write-ColorOutput "❌ 无法自动解决冲突" "Red"
            Write-ColorOutput "`n🔧 建议手动解决:" "Yellow"
            Write-ColorOutput "   1. 运行: git pull origin main" "White"
            Write-ColorOutput "   2. 解决冲突后运行: git push origin main" "White"
            Read-Host "按任意键退出"
            exit 1
        }
    } catch {
        Write-ColorOutput "❌ 自动解决冲突失败: $($_.Exception.Message)" "Red"
        Write-ColorOutput "`n🔧 建议手动解决:" "Yellow"
        Write-ColorOutput "   1. 运行: git pull origin main" "White"
        Write-ColorOutput "   2. 解决冲突后运行: git push origin main" "White"
        Read-Host "按任意键退出"
        exit 1
    }
}

# 显示结果
Write-ColorOutput "`n========================================" "Magenta"
Write-ColorOutput "✅ 推送完成！" "Green"
Write-ColorOutput "========================================" "Magenta"

Show-CommitStats

Write-ColorOutput "`n🌐 远程仓库状态:" "Yellow"
git status --short

Write-ColorOutput "`n🎉 所有操作完成！" "Green"
if (-not $NoConfirm) {
    Read-Host "按任意键退出"
}
