import { searchKeywords } from './threads-keyword-search'

type CliInput = {
  storage_state: string
  query: string
  limit?: number
}

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 posts = await searchKeywords(
    input.storage_state ?? '',
    input.query ?? '',
    input.limit ?? 12,
  )
  process.stdout.write(JSON.stringify({ posts }))
}

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