import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { checkAgentAuth } from '@/lib/agent-auth'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

// GET /api/trades-health — liveness of the trade bot, for the VPS watchdog cron.
// Auth: agent bearer token (same as /api/sync).
// Two independent heartbeats:
//   ingestedAt          — the mini's push loop (POSTs every 15s)
//   profiles[].updatedMs — live_trader itself (state-file mtime, written every poll;
//                          goes stale even when the push loop is still running)
const STORE = path.join(process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'), 'trades-status.json')
const PUSH_STALE_SEC = 300
const BOT_STALE_SEC = 300

export async function GET(req: Request) {
  if (!checkAgentAuth(req)) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  }
  const now = Date.now()
  let data: { ingestedAt?: number; profiles?: { updatedMs?: number | null }[] }
  try {
    data = JSON.parse(fs.readFileSync(STORE, 'utf8'))
  } catch {
    return NextResponse.json({ ok: false, reasons: ['no status file — the mini has never pushed'], pushAgeSec: null, botAgeSec: null, now })
  }
  const pushAgeSec = data.ingestedAt ? Math.round((now - data.ingestedAt) / 1000) : null
  const updates = (data.profiles || []).map(p => p.updatedMs).filter((n): n is number => typeof n === 'number')
  const botAgeSec = updates.length ? Math.round((now - Math.max(...updates)) / 1000) : null
  const reasons: string[] = []
  if (pushAgeSec == null || pushAgeSec > PUSH_STALE_SEC) {
    reasons.push(`push stale: last ingest ${pushAgeSec ?? 'never'}s ago — mini offline or push loop down`)
  }
  if (botAgeSec == null || botAgeSec > BOT_STALE_SEC) {
    reasons.push(`bot stale: newest state write ${botAgeSec ?? 'unknown'}s ago — live_trader down or halted`)
  }
  return NextResponse.json({ ok: reasons.length === 0, reasons, pushAgeSec, botAgeSec, profileCount: (data.profiles || []).length, now })
}
