import type { PanelClient } from "../api/PanelClient.ts";
import type { ChatMessage } from "../types.ts";

type ReservePayload = {
  ok?: boolean;
  accepted?: boolean;
  request_id?: number;
  reason?: string;
  settings?: {
    model?: string;
    personality?: string;
    language?: string;
    max_response_chars?: number;
    native_reply_enabled?: boolean;
  };
};

type AiResult = {
  status: "answered" | "quota_exceeded" | "provider_unavailable" | "error";
  answer?: string;
  actualNeurons?: number;
  errorCode?: string;
};

/**
 * One small, deliberately isolated AI worker.  Normal FilyX messages are
 * immediately handed back to the existing command pipeline; only !ask is put
 * in this bounded queue.  There is one concurrent remote request, no polling
 * loop, no retry storm and no fallback provider, so it cannot make the bot
 * engine CPU-hungry or accidentally create billable traffic.
 */
export class AskProService {
  private readonly pending: ChatMessage[] = [];
  private processing = false;
  private readonly maxLocalQueue = 20;
  private readonly panel: PanelClient;

  constructor(panel: PanelClient) {
    // Node runs TypeScript in strip-only mode on the VPS: avoid constructor
    // parameter properties, which would require a transpilation step.
    this.panel = panel;
  }

  handleMessage(message: ChatMessage): void {
    if (!/^!ask(?:\s|$)/i.test(message.content.trim())) return;
    if (this.pending.length >= this.maxLocalQueue) {
      process.stderr.write(`[FilyX Ask] ignored: local queue full (channel=${message.channel_id})\n`);
      return;
    }
    process.stderr.write(`[FilyX Ask] received (channel=${message.channel_id})\n`);
    this.pending.push(message);
    void this.drain();
  }

  private async drain(): Promise<void> {
    if (this.processing) return;
    this.processing = true;
    try {
      while (this.pending.length) {
        const message = this.pending.shift();
        if (!message) continue;
        await this.process(message);
      }
    } finally {
      this.processing = false;
    }
  }

  private async process(message: ChatMessage): Promise<void> {
    const question = message.content.replace(/^!ask\s*/i, "").trim();
    if (!question || question.length > 300) return;

    let reserved: ReservePayload;
    try {
      reserved = await this.panel.askProReserve({
        channel_id: message.channel_id,
        kick_user_id: message.sender.kick_user_id,
        username: message.sender.username,
        kick_message_id: message.event_id,
        question
      }) as ReservePayload;
    } catch (error) {
      // The panel being briefly busy must not retry or block the normal bot.
      const detail = error instanceof Error ? error.message : "panel unavailable";
      process.stderr.write(`[FilyX Ask] reservation failed (channel=${message.channel_id}): ${detail.slice(0, 180)}\n`);
      return;
    }
    if (!reserved.accepted || !reserved.request_id) {
      process.stderr.write(`[FilyX Ask] ignored (channel=${message.channel_id}, reason=${String(reserved.reason ?? "unknown").slice(0, 80)})\n`);
      return;
    }

    const result = await this.askFreeOnly(question, reserved.settings ?? {});
    try {
      await this.panel.askProComplete({
        request_id: reserved.request_id,
        status: result.status,
        answer: result.answer ?? "",
        actual_neurons: result.actualNeurons ?? 0,
        error_code: result.errorCode ?? ""
      });
      process.stderr.write(`[FilyX Ask] completed (channel=${message.channel_id}, status=${result.status})\n`);
    } catch (error) {
      // A completion is idempotent server-side.  Never make a second AI call.
      const detail = error instanceof Error ? error.message : "panel unavailable";
      process.stderr.write(`[FilyX Ask] completion failed (channel=${message.channel_id}): ${detail.slice(0, 180)}\n`);
    }
  }

  private async askFreeOnly(question: string, settings: NonNullable<ReservePayload["settings"]>): Promise<AiResult> {
    const accountId = (process.env.FILYX_CLOUDFLARE_ACCOUNT_ID ?? "").trim();
    const apiToken = (process.env.FILYX_CLOUDFLARE_AI_TOKEN ?? "").trim();
    // This hard gate is intentional. An incomplete deployment never falls
    // back to another API or a paid Cloudflare entitlement.
    if (!accountId || !apiToken || process.env.FILYX_ASK_FREE_ONLY !== "true") {
      return { status: "error", errorCode: "free_only_not_configured" };
    }

    const maxChars = Math.max(80, Math.min(250, Number(settings.max_response_chars ?? 250)));
    // A compact non-reasoning model keeps this founder preview responsive and
    // stays comfortably inside Cloudflare's daily free allocation.
    const model = "@cf/meta/llama-3.2-1b-instruct";
    const personality = String(settings.personality ?? "direct");
    const tone = personality === "friendly"
      ? "chaleureux et naturel"
      : personality === "humor"
        ? "léger, jamais moqueur"
        : "direct, utile et sobre";
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 8_000);
    try {
      const response = await fetch(
        // Cloudflare's native REST route deliberately contains the model's
        // slash (`@cf/vendor/model`). Encoding it turns the slash into a
        // different route and returns a misleading authentication error.
        `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(accountId)}/ai/run/${model}`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${apiToken}`,
            "Content-Type": "application/json",
            Accept: "application/json"
          },
          signal: controller.signal,
          body: JSON.stringify({
            messages: [
              {
                role: "system",
                content: `Tu es FilyX, assistant de chat Kick. Réponds uniquement en français, ${tone}. Une ou deux phrases, sans markdown, sans promesse, sans données personnelles. Maximum ${maxChars} caractères.`
              },
              { role: "user", content: question }
            ],
            max_completion_tokens: 80,
            temperature: 0.55
          })
        }
      );
      const raw = await response.json().catch(() => ({})) as Record<string, unknown>;
      const errors = Array.isArray(raw.errors) ? raw.errors as Array<Record<string, unknown>> : [];
      const firstCode = String(errors[0]?.code ?? "");
      const detail = String(errors[0]?.message ?? raw.message ?? "");
      if (response.status === 429 || firstCode === "3036") {
        return { status: "quota_exceeded", errorCode: "cloudflare_free_quota" };
      }
      // 5035 is Cloudflare's paid-plan requirement.  Any forbidden/unavailable
      // provider response also fails closed rather than trying a paid backup.
      if (!response.ok || firstCode === "5035" || response.status === 403) {
        return { status: "provider_unavailable", errorCode: `cloudflare_${firstCode || response.status || "unavailable"}`.slice(0, 90) };
      }
      const result = (raw.result ?? {}) as Record<string, unknown>;
      const choices = Array.isArray(result.choices) ? result.choices as Array<Record<string, unknown>> : [];
      const firstChoice = choices[0] ?? {};
      const message = (firstChoice.message ?? {}) as Record<string, unknown>;
      const responseText = String(result.response ?? result.text ?? message.content ?? "")
        .replace(/\s+/g, " ")
        .trim()
        .slice(0, maxChars);
      if (!responseText) return { status: "error", errorCode: "empty_response" };
      const usage = (result.usage ?? raw.usage ?? {}) as Record<string, unknown>;
      const actual = Math.max(1, Math.min(3_000, Number(usage.neurons ?? usage.total_tokens ?? 0) || 0));
      return { status: "answered", answer: responseText, actualNeurons: actual || undefined };
    } catch (error) {
      const code = error instanceof Error && error.name === "AbortError" ? "timeout" : "network";
      return { status: "error", errorCode: code };
    } finally {
      clearTimeout(timer);
    }
  }
}
