# 框选 OCR 识别区域工具 (DPI 感知, 物理像素)

$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# DPI 感知通过 ocr_helper.ps1 提前设置
. (Join-Path $PSScriptRoot "ocr_helper.ps1")

$configDir = Join-Path $PSScriptRoot "config"
$regionFile = Join-Path $configDir "ocr_region.txt"
New-Item -ItemType Directory -Path $configDir -Force | Out-Null

Add-Type -AssemblyName System.Windows.Forms, System.Drawing

$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "  OCR 识别区域 框选工具" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "  屏幕范围 (DPI 感知后, 物理像素): X=$($bounds.Left), Y=$($bounds.Top), $($bounds.Width) x $($bounds.Height)" -ForegroundColor DarkGray
Write-Host ""
Write-Host "  用法:" -ForegroundColor Yellow
Write-Host "    1. 切到 Forza 走到目标界面 (比如 嗯/不 弹框)" -ForegroundColor Gray
Write-Host "    2. Alt+Tab 回到这里, 按回车继续" -ForegroundColor Gray
Write-Host "    3. 屏幕变暗后, 鼠标拖拽框出按钮区域" -ForegroundColor Gray
Write-Host "    4. 松开鼠标 = 确定, ESC = 取消" -ForegroundColor Gray
Write-Host "    5. 框完自动跑 OCR, 只显示关键词命中结果" -ForegroundColor Gray
Write-Host ""
Write-Host "  注意: 框选时确保 Forza 窗口在最上层 (没有被别的窗口遮挡)" -ForegroundColor DarkYellow
Write-Host ""
Read-Host "按回车开始"

$formCode = @"
using System;
using System.Windows.Forms;
public class DBForm : Form {
    public DBForm() {
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
    }
}
"@
try { Add-Type -TypeDefinition $formCode -ReferencedAssemblies System.Windows.Forms -ErrorAction Stop } catch {}

$form = New-Object DBForm
$form.Text = 'AutoDrive 框选'
$form.FormBorderStyle = 'None'
$form.StartPosition = 'Manual'
$form.Location = New-Object System.Drawing.Point $bounds.Left, $bounds.Top
$form.Size = New-Object System.Drawing.Size $bounds.Width, $bounds.Height
$form.TopMost = $true
$form.Opacity = 0.35
$form.BackColor = 'Black'
$form.Cursor = 'Cross'
$form.KeyPreview = $true
$form.ShowInTaskbar = $false

$tip = New-Object Windows.Forms.Label
$tip.AutoSize = $true
$tip.ForeColor = 'White'
$tip.BackColor = 'Transparent'
$tip.Font = New-Object System.Drawing.Font 'Microsoft YaHei', 24, ([System.Drawing.FontStyle]::Bold)
$tip.Text = '拖拽鼠标框出识别区  |  ESC 取消'
$tip.Location = New-Object System.Drawing.Point 80, 80
$form.Controls.Add($tip)

$liveCoord = New-Object Windows.Forms.Label
$liveCoord.AutoSize = $true
$liveCoord.ForeColor = 'Yellow'
$liveCoord.BackColor = 'Transparent'
$liveCoord.Font = New-Object System.Drawing.Font 'Consolas', 20
$liveCoord.Location = New-Object System.Drawing.Point 80, 150
$form.Controls.Add($liveCoord)

$script:startPt = $null
$script:rect = New-Object System.Drawing.Rectangle 0, 0, 0, 0
$script:result = $null

$form.add_MouseDown({
    param($s, $e)
    if ($e.Button -eq 'Left') {
        $script:startPt = $e.Location
        $script:rect = New-Object System.Drawing.Rectangle $e.X, $e.Y, 0, 0
    }
})
$form.add_MouseMove({
    param($s, $e)
    if ($script:startPt) {
        $x = [Math]::Min($script:startPt.X, $e.X)
        $y = [Math]::Min($script:startPt.Y, $e.Y)
        $w = [Math]::Abs($e.X - $script:startPt.X)
        $h = [Math]::Abs($e.Y - $script:startPt.Y)
        $script:rect = New-Object System.Drawing.Rectangle $x, $y, $w, $h
        $screenX = $bounds.Left + $x
        $screenY = $bounds.Top + $y
        $liveCoord.Text = "($screenX, $screenY)  $w x $h"
        $form.Invalidate()
    }
})
$form.add_MouseUp({
    param($s, $e)
    if ($script:startPt -and $script:rect.Width -gt 10 -and $script:rect.Height -gt 10) {
        $script:result = $script:rect
        $form.Close()
    }
    $script:startPt = $null
})
$form.add_Paint({
    param($s, $e)
    if ($script:rect.Width -gt 0 -and $script:rect.Height -gt 0) {
        $pen = New-Object System.Drawing.Pen ([System.Drawing.Color]::Yellow), 4
        $e.Graphics.DrawRectangle($pen, $script:rect)
        $brush = New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(50, 255, 255, 0))
        $e.Graphics.FillRectangle($brush, $script:rect)
        $pen.Dispose(); $brush.Dispose()
    }
})
$form.add_KeyDown({
    param($s, $e)
    if ($e.KeyCode -eq 'Escape') { $script:result = $null; $form.Close() }
})

[void]$form.ShowDialog()
$form.Dispose()

if (-not $script:result) {
    Write-Host "已取消" -ForegroundColor Yellow
    Read-Host "按回车退出"
    exit 0
}

$rClient = $script:result
$r = New-Object System.Drawing.Rectangle ($bounds.Left + $rClient.X), ($bounds.Top + $rClient.Y), $rClient.Width, $rClient.Height
"$($r.X),$($r.Y),$($r.Width),$($r.Height)" | Set-Content -LiteralPath $regionFile -Encoding UTF8
Write-Host ""
Write-Host "[√] 保存识别区 (物理像素): ($($r.X), $($r.Y)) $($r.Width) x $($r.Height)" -ForegroundColor Green
Write-Host "[√] 配置: $regionFile" -ForegroundColor Green

$shotPath = Join-Path $configDir "ocr_region_preview.png"
$preview = Get-ScreenRegionBitmap -X $r.X -Y $r.Y -W $r.Width -H $r.Height
$preview.Save($shotPath, [System.Drawing.Imaging.ImageFormat]::Png)
$preview.Dispose()
Write-Host "[√] 截图: $shotPath  (打开看看是否框对了)" -ForegroundColor Green

Write-Host ""
Write-Host "--- OCR 测试 ---" -ForegroundColor Cyan
$t0 = [DateTime]::Now
try {
    $text = Invoke-OcrOnScreen -X $r.X -Y $r.Y -W $r.Width -H $r.Height
} catch {
    Write-Host "[X] OCR 测试失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "    请按 说明.txt 安装简体中文 OCR 组件后, 再重新框选。" -ForegroundColor Yellow
    Read-Host "按回车退出"
    exit 1
}
$ms = [int]([DateTime]::Now - $t0).TotalMilliseconds
Write-Host "耗时: ${ms}ms" -ForegroundColor DarkGray
Write-Host ""
Write-Host "OCR 测试完成, 不显示识别原文, 只显示关键词命中结果。" -ForegroundColor Yellow

$keywords = @('开始竞赛赛事', '重新开始', '嗯', '不')
Write-Host "关键词命中:" -ForegroundColor Cyan
foreach ($k in $keywords) {
    $hit = $text -match [regex]::Escape($k)
    $color = if ($hit) { 'Green' } else { 'DarkGray' }
    $mark = if ($hit) { '√' } else { 'x' }
    Write-Host "  [$mark] $k" -ForegroundColor $color
}

Write-Host ""
Write-Host "如果识别错或漏了关键词, 重新运行本工具调整识别区" -ForegroundColor DarkYellow
Read-Host "按回车退出"
