import { runUserMessage } from "../runner";
import { loadSettings } from "../config";
import { checkExistingDaemon } from "../pid";

export async function send(args: string[] = []): Promise<void> {
  const hasTelegramFlag = args.includes("--telegram");
  const prompt = args.filter((a) => !a.startsWith("--")).join(" ").trim();

  if (!prompt) {
    console.error("Usage: qwenclaw send [--telegram] <prompt>");
    process.exit(1);
  }

  const existingPid = await checkExistingDaemon();
  if (!existingPid) {
    console.error("QwenClaw daemon is not running. Start it with `qwenclaw start`.");
    process.exit(1);
  }

  const settings = await loadSettings();

  console.log(`Sending prompt to daemon: "${prompt.slice(0, 60)}${prompt.length > 60 ? "..." : ""}"`);

  const result = await runUserMessage("send", prompt);
  console.log(result.stdout);

  if (hasTelegramFlag && settings.telegram.token && settings.telegram.allowedUserIds.length > 0) {
    const { sendMessage } = await import("./telegram");
    const text = result.exitCode === 0 ? result.stdout : `Error: ${result.stderr || "Unknown error"}`;
    for (const userId of settings.telegram.allowedUserIds) {
      await sendMessage(settings.telegram.token, userId, text).catch((err) => {
        console.error(`[Telegram] Failed to send to ${userId}: ${err instanceof Error ? err.message : err}`);
      });
    }
  }

  if (result.exitCode !== 0) {
    process.exit(result.exitCode);
  }
}
