import { loadConfig } from "./src/config.ts"
import { sendMessage, sendDocument, sendPhoto } from "./src/api.ts"

function parseArgs(argv: string[]): { action: string; opts: Record<string, string> } {
  const action = argv[0] ?? ""
  const opts: Record<string, string> = {}
  for (let i = 1; i < argv.length; i++) {
    const a = argv[i]
    if (a.startsWith("--")) {
      const key = a.slice(2)
      const val = argv[i + 1] ?? ""
      opts[key] = val
      i++
    }
  }
  return { action, opts }
}

async function main(): Promise<void> {
  const argv = process.argv.slice(2)
  if (argv.length < 1) {
    process.stderr.write('usage: node cli.ts <text|document|photo> --text "..." [--chat-id ...] [--path ...] [--caption ...] [--parse-mode MarkdownV2|HTML|plain]\n')
    process.exit(2)
  }

  const { action, opts } = parseArgs(argv)
  const chatIdOverride = opts["chat-id"] ? { chatId: opts["chat-id"] } : undefined
  const { token, chatId } = loadConfig(chatIdOverride)
  const parseMode = (opts["parse-mode"] ?? "MarkdownV2") as "MarkdownV2" | "HTML" | "plain"

  let result
  if (action === "text") {
    if (!opts.text) {
      process.stderr.write('error: --text is required for action "text"\n')
      process.exit(2)
    }
    result = await sendMessage(token, chatId, opts.text, parseMode)
  } else if (action === "document") {
    if (!opts.path) {
      process.stderr.write('error: --path is required for action "document"\n')
      process.exit(2)
    }
    result = await sendDocument(token, chatId, opts.path, opts.caption, parseMode)
  } else if (action === "photo") {
    if (!opts.path) {
      process.stderr.write('error: --path is required for action "photo"\n')
      process.exit(2)
    }
    result = await sendPhoto(token, chatId, opts.path, opts.caption, parseMode)
  } else {
    process.stderr.write(`error: unknown action "${action}" (expected: text|document|photo)\n`)
    process.exit(2)
  }

  console.log(JSON.stringify(result))
}

main().catch((err: unknown) => {
  const msg = err instanceof Error ? err.message : String(err)
  process.stderr.write(`⚠️ telegram-send failed (exit 1): ${msg}\n`)
  process.exit(1)
})