# claim-points.ps1
# 通过 Windows UI Automation 自动在 WorkBuddy 客户端寻找并点击「领取今日礼包」按钮
# 用法：
#   .\claim-points.ps1 -Mode auto   # 自动寻找并点击（由 bridge 调用）
#   .\claim-points.ps1 -Mode list   # 仅列出客户端所有按钮（用于调研）
# 退出码：0=成功点击，1=未找到 WorkBuddy，2=未找到目标按钮

param(
  [ValidateSet('auto','list')]
  [string]$Mode = 'auto'
)

Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes

$ErrorActionPreference = 'Continue'
$Out = { param($msg, $color='Cyan') Write-Host "[claim-points] $msg" -ForegroundColor $color }
$KEYWORDS = @('领取今日','领取礼','领取','礼盒','签到','每日积分','今日积分')

function Find-WorkBuddyWindow {
  $root = [System.Windows.Automation.AutomationElement]::RootElement
  # 1) 按窗口 Name 找（最常见）
  $procNames = @('WorkBuddy','CodeBuddy')
  foreach ($pn in $procNames) {
    $procs = Get-Process -Name $pn -ErrorAction SilentlyContinue
    if ($procs) {
      foreach ($p in $procs) {
        $cond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$p.Id)
        $win = $root.FindFirst([System.Windows.Automation.TreeScope]::Children, $cond)
        if ($win) { return $win }
      }
    }
  }
  # 2) 兜底：按 Name 找
  $nameCond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::NameProperty, 'WorkBuddy')
  $w = $root.FindFirst([System.Windows.Automation.TreeScope]::Children, $nameCond)
  if ($w) { return $w }
  return $null
}

function Get-AllClickables($root) {
  $btn = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, [System.Windows.Automation.ControlType]::Button)
  $link = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, [System.Windows.Automation.ControlType]::Hyperlink)
  $img = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, [System.Windows.Automation.ControlType]::Image)
  $list = @()
  $list += $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $btn)
  $list += $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $link)
  $list += $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $img)
  return $list
}

function Format-Box($el) {
  $box = $el.Current.BoundingRectangle
  if ([double]::IsInfinity($box.X) -or [double]::IsInfinity($box.Y)) { return '(0,0)' }
  return ('({0},{1})' -f [int]$box.X, [int]$box.Y)
}

& $Out "查找 WorkBuddy 客户端窗口..."
$wb = Find-WorkBuddyWindow
if (-not $wb) {
  & $Out "未找到 WorkBuddy 客户端窗口，请先打开 WorkBuddy 并登录" 'Red'
  exit 1
}
& $Out "已找到窗口: $($wb.Current.Name)"

$all = Get-AllClickables $wb
& $Out "枚举到 $($all.Count) 个可点击/链接/图片控件"

# 列出（无论模式都打）
& $Out "--- 控件列表 ---"
foreach ($c in $all) {
  $nm = $c.Current.Name
  if ($nm) {
    $type = $c.Current.ControlType.ProgrammaticName -replace 'ControlType\.',''
    & $Out "  $type : '$nm'  @$(Format-Box $c)"
  }
}

if ($Mode -eq 'list') {
  & $Out "Mode=list 已完成，未执行点击"
  exit 0
}

# 匹配关键词
& $Out "--- 关键词匹配 ---"
$target = $null
$matched = @()
foreach ($c in $all) {
  $nm = $c.Current.Name
  if (-not $nm) { continue }
  foreach ($kw in $KEYWORDS) {
    if ($nm -like "*$kw*") {
      $matched += [PSCustomObject]@{Name=$nm; Kw=$kw; Element=$c}
      if (-not $target) { $target = $c }
      break
    }
  }
}
foreach ($m in $matched) { & $Out "  ✓ 命中 '$($m.Kw)': '$($m.Name)'" }

if (-not $target) {
  & $Out "未找到匹配按钮" 'Yellow'
  & $Out "请把上面「控件列表」中含「领取」「礼盒」「签到」「积分」等字样的控件名发给我" 'Yellow'
  exit 2
}

# 点击
try {
  $invokePattern = $target.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern)
  if ($invokePattern) {
    $invokePattern.Invoke()
    & $Out "已点击按钮: '$($target.Current.Name)'"
  } else {
    # 用 SelectionItemPattern 兜底
    $sel = $target.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern)
    $sel.Select()
    & $Out "用 Select 触发: '$($target.Current.Name)'"
  }
} catch (e) {
  & $Out "点击失败: $($e.Exception.Message)" 'Red'
  exit 3
}

# 二次匹配：有时点击后弹出菜单含「领取今日礼包」
Start-Sleep -Milliseconds 1500
$wb2 = Find-WorkBuddyWindow
if ($wb2) {
  $all2 = Get-AllClickables $wb2
  foreach ($c in $all2) {
    $nm = $c.Current.Name
    if ($nm -and ($nm -like "*领取今日*" -or $nm -like "*领取礼*")) {
      try {
        $c.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()
        & $Out "二次点击(弹窗内): '$nm'"
      } catch {}
      break
    }
  }
}

& $Out "完成"
exit 0
