# 强制使用 TLS 1.2，解决 SSL/TLS 错误
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 设置文件路径
$vlessFile = "$PSScriptRoot\vless.txt"
$htmlFile = "$PSScriptRoot\vless_links.html"

# 清空旧文件
if (Test-Path $vlessFile) { Clear-Content -Path $vlessFile }
if (Test-Path $htmlFile) { Remove-Item -Path $htmlFile }

# 获取域名列表和模板
try {
    $domains = (Invoke-WebRequest -Uri "http://abcd123.webn.cc/b.txt" -UseBasicParsing).Content -split "`n" | 
               Where-Object { $_.Trim() -ne "" } | ForEach-Object { $_.Trim() }
    $templates = (Invoke-WebRequest -Uri "http://abcd123.webn.cc/bb.txt" -UseBasicParsing).Content -split "`n" | 
                 Where-Object { $_.Trim() -ne "" } | ForEach-Object { $_.Trim() }
} catch {
    Write-Host "❌ 网络请求失败，请检查 TLS 设置或目标网址是否可访问: $_"
    exit
}

# 检查域名和模板是否为空
if ($domains.Count -eq 0 -or $templates.Count -eq 0) {
    Write-Host "❌ 域名或模板列表为空，无法生成链接"
    exit
}

# 生成链接并写入 vless.txt
$links = @()
for ($i = 0; $i -lt 20; $i++) {
    $domain = Get-Random -InputObject $domains
    $template = Get-Random -InputObject $templates
    $link = $template -replace "88888888", $domain
    # 修改别名，格式为 番茄节点--001 到 番茄节点--020
    $newRemark = "番茄plus--{0:D3}" -f ($i + 1)
    # 替换 # 后的内容为新别名，如果没有 #，则添加
    if ($link -match "#") {
        $link = $link -replace "#.*", "#$newRemark"
    } else {
        $link = "$link#$newRemark"
    }
    $links += $link
    Add-Content -Path $vlessFile -Value $link
}

# 调试：输出生成的链接以检查完整性
Write-Host "✅ 生成的 VLESS 链接："
$links | ForEach-Object { Write-Host $_ }

# 构建 HTML 内容
$htmlLines = @()
$htmlLines += '<!DOCTYPE html>'
$htmlLines += '<html>'
$htmlLines += '<head>'
$htmlLines += '<meta charset="UTF-8">'
$htmlLines += '<title>生成的 VLESS 链接</title>'
$htmlLines += '<style>'
$htmlLines += 'body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; }'
$htmlLines += 'h2 { color: #333; }'
$htmlLines += 'ul { list-style-type: none; padding: 0; }'
$htmlLines += 'li { margin: 8px 0; font-family: monospace; word-break: break-word; }'
$htmlLines += '.button-container { margin-bottom: 20px; }'
$htmlLines += 'button, .link-button { background-color: #0078D4; color: white; border: none; padding: 10px 16px; font-size: 16px; cursor: pointer; border-radius: 4px; display: inline-block; margin-right: 10px; text-decoration: none; }'
$htmlLines += 'button:hover, .link-button:hover { background-color: #005A9E; }'
$htmlLines += '</style>'
$htmlLines += '</head>'
$htmlLines += '<body>'
$htmlLines += '<h2>✅ 生成20条 VLESS 链接</h2>'
$htmlLines += '<div class="button-container">'
$htmlLines += '<button onclick="copyAllLinks()">📋 复制全部链接</button>'
$htmlLines += '<a href="https://www.youtube.com/@%E7%95%AA%E8%8C%84plus" class="link-button" target="_blank">🌐 跳转到 @番茄plus</a>'
$htmlLines += '</div>'
$htmlLines += '<ul id="linkList">'
foreach ($link in $links) {
    # HTML 显示时转义特殊字符
    $safeLink = $link -replace "&", "&amp;" -replace "<", "&lt;" -replace ">", "&gt;" -replace '"', "&quot;" -replace "'", "&#39;"
    $htmlLines += "<li>$safeLink</li>"
}
$htmlLines += '</ul>'
$htmlLines += '<textarea id="hiddenLinks" style="display:none;">'
# 直接写入原始链接，使用 \n 分隔
$htmlLines += ($links -join "`n")
$htmlLines += '</textarea>'
$htmlLines += '<script>'
$htmlLines += 'function copyAllLinks() {'
$htmlLines += ' const text = document.getElementById("hiddenLinks").value;'
$htmlLines += ' navigator.clipboard.writeText(text).then(() => {'
$htmlLines += ' alert("✅ 已复制全部链接到剪贴板");'
$htmlLines += ' }).catch(err => {'
$htmlLines += ' alert("❌ 复制全部链接失败：" + err);'
$htmlLines += ' });'
$htmlLines += '}'
$htmlLines += '</script>'
$htmlLines += '</body>'
$htmlLines += '</html>'

# 使用 StreamWriter 写入 UTF-8 带 BOM
try {
    $encoding = New-Object System.Text.UTF8Encoding $true
    $writer = New-Object System.IO.StreamWriter($htmlFile, $false, $encoding)
    foreach ($line in $htmlLines) {
        $writer.WriteLine($line)
    }
    $writer.Close()
} catch {
    Write-Host "❌ 写入 HTML 文件失败: $_"
    exit
}

# 打开浏览器
if (Test-Path $htmlFile) {
    try {
        Start-Process $htmlFile
    } catch {
        Write-Host "❌ 无法打开 HTML 文件: $_"
    }
} else {
    Write-Host "❌ HTML 文件未生成，无法打开"
}
# 删除 vless.txt 文件
if (Test-Path $vlessFile) {
    try {
        Remove-Item -Path $vlessFile -Force
    } catch {
        Write-Host "⚠️ 删除 vless.txt 失败: $_"
    }
}
