import { SlashCommandBuilder } from "discord.js";
import type { CommandModule } from "../../discord/types.js";
import {
  summarizeService,
  type SummarizeEngine,
  type SummarizeMode,
} from "../../services/summarize/summarize-service.js";

function chunkText(text: string, maxLen = 1800): string[] {
  const chunks: string[] = [];
  let rest = String(text || "").trim();
  while (rest.length > maxLen) {
    const cut = rest.lastIndexOf("\n", maxLen);
    const idx = cut > 200 ? cut : maxLen;
    chunks.push(rest.slice(0, idx).trim());
    rest = rest.slice(idx).trim();
  }
  if (rest) chunks.push(rest);
  return chunks;
}

export const summarizeCommand: CommandModule = {
  data: new SlashCommandBuilder()
    .setName("summarize")
    .setDescription("웹페이지를 요약합니다")
    .addStringOption((opt) => opt.setName("url").setDescription("요약할 URL").setRequired(true))
    .addStringOption((opt) =>
      opt
        .setName("mode")
        .setDescription("모델 선택 모드")
        .setRequired(false)
        .addChoices(
          { name: "auto", value: "auto" },
          { name: "fast", value: "fast" },
          { name: "quality", value: "quality" },
        ),
    )
    .addStringOption((opt) =>
      opt
        .setName("engine")
        .setDescription("요약 엔진")
        .setRequired(false)
        .addChoices(
          { name: "ai", value: "ai" },
          { name: "basic", value: "basic" },
          { name: "both", value: "both" },
        ),
    ),
  async execute(interaction) {
    const url = interaction.options.getString("url", true);
    const mode = (interaction.options.getString("mode") || "auto") as SummarizeMode;
    const engine = (interaction.options.getString("engine") || "basic") as SummarizeEngine | "both";

    await interaction.deferReply();
    try {
      const aiResult =
        engine === "ai" || engine === "both"
          ? await summarizeService.summarizeUrl(url, mode, "ai")
          : null;
      const basicResult =
        engine === "basic" || engine === "both"
          ? await summarizeService.summarizeUrl(url, mode, "basic")
          : null;

      const ref = aiResult || basicResult;
      const sections: string[] = [];
      if (aiResult) {
        sections.push(`**[AI 요약]** model=\`${aiResult.model}\` call#${aiResult.callNo}\n${aiResult.summary}`);
      }
      if (basicResult) {
        sections.push(
          `**[비AI 요약]** model=\`${basicResult.model}\` call#${basicResult.callNo}\n${basicResult.summary}`,
        );
      }

      const header = `**요약 완료**\n제목: ${ref?.title || "N/A"}\n원문: <${ref?.sourceUrl || url}>`;
      const chunks = chunkText(`${header}\n\n${sections.join("\n\n")}`, 1800);
      await interaction.editReply(chunks[0]);
      for (let i = 1; i < chunks.length; i += 1) {
        await interaction.followUp(chunks[i]);
      }
    } catch (error) {
      await interaction.editReply(
        `요약 실패: ${error instanceof Error ? error.message : "알 수 없는 오류"}`,
      );
    }
  },
};
