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

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

async function readStdin(): Promise<string> {
  const chunks: Buffer[] = []
  for await (const chunk of process.stdin) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
  }
  return Buffer.concat(chunks).toString('utf8')
}

async function main() {
  const raw = await readStdin()
  const input = JSON.parse(raw) as CliInput
  const mediaId = await resolveMediaIdFromPermalink(input.permalink ?? '', input.storage_state ?? '')
  if (!mediaId) {
    throw new Error('無法從 permalink 解析 Threads media id')
  }
  process.stdout.write(JSON.stringify({ mediaId }))
}

main().catch((error) => {
  const message = error instanceof Error ? error.message : String(error)
  process.stderr.write(message)
  process.exit(1)
})