#!/usr/bin/env node
// Delete the test bot's leftover E2E posts — any status whose text contains the
// compose flow's marker ("halflight e2e"). A §10 safety-net: the compose flow
// deletes its own post via the UI, but a crashed/aborted run can leave one
// behind. Safe to run ad-hoc, and run-e2e.sh can call it after the flow.
//
// Slot-keyed output only — never prints a hostname into the terminal scrollback.

import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = dirname(fileURLToPath(import.meta.url))
const MARKER = 'halflight e2e'

function resolveRigPath() {
  const fromArg = process.argv[2]
  if (fromArg && fromArg.length > 0) return fromArg
  const env = process.env.HALFLIGHT_TEST_RIG
  if (env && env.length > 0) return env
  return resolve(__dirname, '..', '..', 'secrets', 'test-rigs', 'halflight.test.json')
}

async function cleanupSlot(slot, entry) {
  const base = `https://${entry.instance}`
  const headers = { Authorization: `Bearer ${entry.accessToken}`, Accept: 'application/json' }
  let resp
  try {
    resp = await fetch(`${base}/api/v1/accounts/${entry.userId}/statuses?limit=40`, { headers })
  } catch (e) {
    console.warn(`[cleanup] ${slot}: list error — ${e.message}`)
    return
  }
  if (!resp.ok) {
    console.warn(`[cleanup] ${slot}: list returned HTTP ${resp.status}`)
    return
  }
  const statuses = await resp.json()
  const targets = (Array.isArray(statuses) ? statuses : []).filter(
    (s) => typeof s?.content === 'string' && s.content.includes(MARKER)
  )
  let deleted = 0
  for (const s of targets) {
    try {
      const d = await fetch(`${base}/api/v1/statuses/${s.id}`, { method: 'DELETE', headers })
      if (d.ok) deleted++
      else console.warn(`[cleanup] ${slot}: delete ${s.id} → HTTP ${d.status}`)
    } catch (e) {
      console.warn(`[cleanup] ${slot}: delete ${s.id} error — ${e.message}`)
    }
  }
  console.log(`[cleanup] ${slot}: removed ${deleted} marker post(s) (of ${targets.length} found).`)
}

async function main() {
  let parsed
  try {
    parsed = JSON.parse(readFileSync(resolveRigPath(), 'utf8'))
  } catch {
    console.log('[cleanup] no usable rig file — nothing to clean.')
    return
  }
  const rigs = parsed.rigs ?? {}
  const targets = Object.entries(rigs).filter(([, e]) => e && e.type === 'pixelfed')
  if (targets.length === 0) {
    console.log('[cleanup] no pixelfed slot — nothing to clean.')
    return
  }
  for (const [slot, entry] of targets) await cleanupSlot(slot, entry)
}

await main()
