import { spawnSync } from "child_process"
import { tool } from "@opencode-ai/plugin"
import path from "path"

export default tool({
  description: "Send a message, document, or photo to Telegram via Bot API. Supports MarkdownV2/HTML/plain text. Returns { ok, message_id, chat_id }. Requires TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID env vars.",
  args: {
    action: tool.schema.enum(["text", "document", "photo"]).describe("Type of send: text message, document file, or photo image"),
    chat_id: tool.schema.string().optional().describe("Override default TELEGRAM_CHAT_ID"),
    text: tool.schema.string().optional().describe("Message text (required for action=text)"),
    path: tool.schema.string().optional().describe("Absolute path to file (required for action=document/photo)"),
    caption: tool.schema.string().optional().describe("Caption for document/photo"),
    parse_mode: tool.schema.enum(["MarkdownV2", "HTML", "plain"]).optional().describe("Parse mode, default MarkdownV2"),
  },
  async execute(args, context) {
    const telegramDir = path.resolve(import.meta.dir, "..", "telegram")
    const cliPath = path.join(telegramDir, "cli.ts")

    const cliArgs = [args.action]
    if (args.chat_id) cliArgs.push("--chat-id", args.chat_id)
    if (args.text) cliArgs.push("--text", args.text)
    if (args.path) cliArgs.push("--path", args.path)
    if (args.caption) cliArgs.push("--caption", args.caption)
    if (args.parse_mode) cliArgs.push("--parse-mode", args.parse_mode)

    const r = spawnSync("node", ["--experimental-strip-types", cliPath, ...cliArgs], {
      encoding: "utf-8",
      cwd: context.worktree,
    })
    if (r.status !== 0) {
      return `⚠️ telegram-send failed (exit ${r.status}): ${r.stderr || r.stdout}`
    }
    return r.stdout.trim()
  },
})