import http from 'node:http'
import { resolveMediaIdFromPermalink } from './threads-resolve-media'

const port = Number(process.env.PORT ?? process.env.HAIXUN_NODE_TOOL_PORT ?? 9102)

type ResolveInput = {
  permalink?: string
  storage_state?: string
}

async function readJson(req: http.IncomingMessage): Promise<ResolveInput> {
  const chunks: Buffer[] = []
  for await (const chunk of req) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
  }
  if (chunks.length === 0) return {}
  return JSON.parse(Buffer.concat(chunks).toString('utf8')) as ResolveInput
}

function writeJson(res: http.ServerResponse, status: number, body: unknown) {
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
  res.end(JSON.stringify(body))
}

const server = http.createServer(async (req, res) => {
  try {
    if (req.method === 'GET' && req.url === '/health') {
      writeJson(res, 200, { ok: true })
      return
    }
    if (req.method !== 'POST' || req.url !== '/resolve') {
      writeJson(res, 404, { error: 'not found' })
      return
    }
    const input = await readJson(req)
    const mediaId = await resolveMediaIdFromPermalink(input.permalink ?? '', input.storage_state ?? '')
    if (!mediaId) {
      writeJson(res, 404, { error: 'media id not found' })
      return
    }
    writeJson(res, 200, { mediaId })
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    writeJson(res, 500, { error: message })
  }
})

server.listen(port, '0.0.0.0', () => {
  console.log(`[resolve-media-tool] listening on :${port}`)
})
