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

export const runtime = 'nodejs'

// POST /api/trades-ingest — the mini pushes its trade-bot status here.
// Auth: the agent bearer token (AGENT_TOKEN), same as the other agent routes.
const DIR = process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads')
const STORE = path.join(DIR, 'trades-status.json')
const COMMANDS = path.join(DIR, 'trades-commands.json')

export async function POST(req: Request) {
  if (!checkAgentAuth(req)) {
    return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  }
  let body: unknown
  try {
    body = await req.json()
  } catch {
    return NextResponse.json({ error: 'bad json' }, { status: 400 })
  }
  const profiles = (body as { profiles?: unknown })?.profiles
  if (!Array.isArray(profiles)) {
    return NextResponse.json({ error: 'profiles[] required' }, { status: 400 })
  }
  const plays = Array.isArray((body as { plays?: unknown })?.plays) ? (body as { plays: unknown[] }).plays : []
  const analytics = (body as { analytics?: unknown })?.analytics ?? null
  const capital = Array.isArray((body as { capital?: unknown })?.capital) ? (body as { capital: unknown[] }).capital : []
  const settings = (body as { settings?: unknown })?.settings ?? null
  const fund = (body as { fund?: unknown })?.fund ?? null
  const token = (body as { token?: unknown })?.token ?? null
  // drain any pending control commands and hand them back to the mini (delivered once)
  let commands: unknown[] = []
  try {
    commands = JSON.parse(fs.readFileSync(COMMANDS, 'utf8'))
    if (!Array.isArray(commands)) commands = []
  } catch { commands = [] }
  try {
    fs.mkdirSync(DIR, { recursive: true })
    fs.writeFileSync(STORE, JSON.stringify({ profiles, plays, analytics, capital, settings, fund, token, ingestedAt: Date.now() }))
    if (commands.length) fs.writeFileSync(COMMANDS, '[]')  // clear on delivery
  } catch {
    return NextResponse.json({ error: 'store failed' }, { status: 500 })
  }
  return NextResponse.json({ ok: true, count: profiles.length, commands })
}
