# daily_news_sender.ps1
# 功能：每天最多执行一次，生成新闻并发送到 QQ
# 使用场景：OpenClaw HEARTBEAT 调用

$ErrorActionPreference = "Stop"

# 配置
$skillDir = "C:\Users\Administrator\.openclaw\workspace\skills\news-aggregator-1.0.3"
$nodeExe = "node"
$indexJs = Join-Path $skillDir "index.js"
$outputMd = Join-Path $skillDir "news_aggregated.md"
$markerFile = Join-Path $skillDir ".last_sent"
$targetQQ = "B5BCB78A685A18DC20FCFD3ED61356F8"

# 检查是否已发送（防止重复）
$today = Get-Date -Format "yyyy-MM-dd"
if (Test-Path $markerFile) {
  $lastSent = Get-Content $markerFile -Raw
  if ($lastSent -eq $today) {
    Write-Host "[NewsAggregator] Already sent today ($today). Skipping."
    exit 0
  }
}

# 时间窗口：7:00-7:05 之间才执行
$hour = (Get-Date).Hour
$minute = (Get-Date).Minute
if ($hour -ne 7 -or $minute -gt 5) {
  Write-Host "[NewsAggregator] Not in 07:00-07:05 window. Skipping."
  exit 0
}

Write-Host "[NewsAggregator] Running aggregation..."
& $nodeExe $indexJs
if ($LASTEXITCODE -ne 0) {
  Write-Error "Aggregation failed."
  exit 1
}

# 检查输出文件
if (-not (Test-Path $outputMd)) {
  Write-Error "Output not found: $outputMd"
  exit 1
}

Write-Host "[NewsAggregator] Sending to QQ $targetQQ ..."
# 使用 openclaw CLI 发送（需要已登录）
$sendArgs = "message send --channel qqbot --to $targetQQ --file `"$outputMd`""
& openclaw $sendArgs
if ($LASTEXITCODE -ne 0) {
  Write-Warning "Send failed (openclaw may not be available). Will retry later."
  exit 1
}

# 标记今天已发送
Set-Content -Path $markerFile -Value $today -Encoding UTF8
Write-Host "[NewsAggregator] Sent successfully."
