@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul 2>&1
echo ========================================
echo 代码文件编码批量转换工具
echo ========================================
echo.

:: 设置要扫描的文件扩展名
set "extensions=*.py *.java *.js *.ts *.html *.css *.xml *.json *.md *.txt *.bat *.cmd *.ps1 *.sh *.yml *.yaml *.ini *.cfg *.conf *.properties"

:: 设置目标目录（默认为当前目录）
set "target_dir=%cd%"
if not "%~1"=="" set "target_dir=%~1"

echo 目标目录: %target_dir%
echo.

:: 检查目录是否存在
if not exist "%target_dir%" (
    echo 错误：指定的目录不存在
    pause
    exit /b 1
)

:: 创建临时目录
set "temp_dir=%temp%\encoding_convert_%random%"
mkdir "%temp_dir%"

:: 统计变量
set "total_files=0"
set "converted_files=0"
set "skipped_files=0"

echo 开始扫描文件...
echo.

:: 遍历所有指定扩展名的文件
for %%e in (%extensions%) do (
    for /r "%target_dir%" %%f in (%%e) do (
        set /a total_files+=1
        call :process_file "%%f"
    )
)

echo.
echo ========================================
echo 转换完成
echo ========================================
echo 总文件数: %total_files%
echo 已转换: %converted_files%
echo 已跳过: %skipped_files%
echo.

:: 清理临时目录
rd /s /q "%temp_dir%" 2>nul

pause
exit /b

:process_file
set "file=%~1"
set "is_utf8=0"

:: 检查文件是否已经是UTF-8编码
powershell -Command "try { $content = [System.IO.File]::ReadAllText('%file%', [System.Text.Encoding]::UTF8); $content | Out-Null; exit 0 } catch { exit 1 }" >nul 2>&1
if %errorlevel% equ 0 set "is_utf8=1"

if %is_utf8% equ 1 (
    echo [跳过] %file% (已经是UTF-8)
    set /a skipped_files+=1
) else (
    echo [转换] %file%
    
    :: 尝试检测并转换编码
    powershell -Command ^
        "$path = '%file%'; ^
        try { ^
            $bytes = [System.IO.File]::ReadAllBytes($path); ^
            $encoding = [System.Text.Encoding]::GetEncoding('GB2312'); ^
            $content = $encoding.GetString($bytes); ^
            [System.IO.File]::WriteAllText($path, $content, [System.Text.Encoding]::UTF8); ^
            exit 0 ^
        } catch { ^
            exit 1 ^
        }"
    
    if %errorlevel% equ 0 (
        set /a converted_files+=1
    ) else (
        echo [警告] 无法转换 %file%
    )
)
goto :eof
