$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$projectDirectory = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))
$toolDirectory = Join-Path $projectDirectory ".voice_tools"
$pythonDirectory = Join-Path $toolDirectory "python"
$pythonExecutable = Join-Path $pythonDirectory "python.exe"
$pythonVersion = "3.12.10"
$pythonArchive = Join-Path $toolDirectory "python-embed-amd64.zip"
$pythonUrl = "https://www.python.org/ftp/python/$pythonVersion/python-$pythonVersion-embed-amd64.zip"
$getPipPath = Join-Path $toolDirectory "get-pip.py"
$getPipUrl = "https://bootstrap.pypa.io/get-pip.py"

New-Item -ItemType Directory -Force -Path $toolDirectory | Out-Null

if (-not (Test-Path -LiteralPath $pythonExecutable)) {
    Write-Host "[1/4] 正在从 Python 官方网站下载便携 Python $pythonVersion ..."
    Invoke-WebRequest -UseBasicParsing -Uri $pythonUrl -OutFile $pythonArchive
    if ((Get-Item -LiteralPath $pythonArchive).Length -lt 5MB) {
        throw "便携 Python 下载不完整。"
    }
    New-Item -ItemType Directory -Force -Path $pythonDirectory | Out-Null
    Expand-Archive -LiteralPath $pythonArchive -DestinationPath $pythonDirectory -Force

    $pathFile = Get-ChildItem -LiteralPath $pythonDirectory -Filter "python*._pth" | Select-Object -First 1
    if ($null -eq $pathFile) {
        throw "没有找到便携 Python 的路径配置文件。"
    }
    @(
        "python312.zip"
        "."
        "Lib\site-packages"
        "import site"
    ) | Set-Content -LiteralPath $pathFile.FullName -Encoding ASCII
}
else {
    Write-Host "[1/4] 便携 Python 已存在，跳过下载。"
}

if (-not (Test-Path -LiteralPath (Join-Path $pythonDirectory "Lib\site-packages\pip"))) {
    Write-Host "[2/4] 正在从 Python 官方网站安装 pip ..."
    Invoke-WebRequest -UseBasicParsing -Uri $getPipUrl -OutFile $getPipPath
    & $pythonExecutable $getPipPath --disable-pip-version-check
    if ($LASTEXITCODE -ne 0) {
        throw "pip 安装失败。"
    }
}
else {
    Write-Host "[2/4] pip 已存在，跳过安装。"
}

Write-Host "[3/4] 正在从 PyPI 官方仓库安装 edge-tts 7.2.8 ..."
& $pythonExecutable -m pip install --disable-pip-version-check --upgrade "edge-tts==7.2.8"
if ($LASTEXITCODE -ne 0) {
    throw "edge-tts 安装失败。"
}

Write-Host "[4/4] 正在生成并接入樱井澪的 56 句配音 ..."
& $pythonExecutable (Join-Path $PSScriptRoot "generate_mio_voices.py")
if ($LASTEXITCODE -ne 0) {
    throw "配音生成未完成。重新运行本工具会自动续传。"
}

$renpySdk = "D:\迅雷下载\renpy-8.5.3-sdk"
$renpyPython = Join-Path $renpySdk "lib\py3-windows-x86_64\python.exe"
$renpyMain = Join-Path $renpySdk "renpy.py"
if ((Test-Path -LiteralPath $renpyPython) -and (Test-Path -LiteralPath $renpyMain)) {
    Write-Host "正在运行 Ren'Py 完整性检查 ..."
    & $renpyPython $renpyMain $projectDirectory lint
    if ($LASTEXITCODE -ne 0) {
        throw "配音已生成，但 Ren'Py 完整性检查未通过。"
    }
}

Write-Host ""
Write-Host "完成：56 句女主配音已经接入 SakuraMemory。" -ForegroundColor Green

