"use client";

export type AiProvider = "online" | "local" | "ollama" | "codex";

export type AiPanelPrefs = {
  provider: AiProvider;
  model: string;
  modelKey?: string;
  profileId?: string;
  maxSteps: number;
};

export const parseSseChunks = async (
  res: Response,
  onEvent: (event: string, dataText: string) => void,
) => {
  if (!res.body) throw new Error("响应不支持流式读取");
  const reader = res.body.getReader();
  const decoder = new TextDecoder("utf-8");

  let buffer = "";
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    while (true) {
      const sep = buffer.indexOf("\n\n");
      if (sep === -1) break;
      const raw = buffer.slice(0, sep);
      buffer = buffer.slice(sep + 2);

      if (raw.trimStart().startsWith(":")) continue;

      const lines = raw.split(/\r?\n/);
      let event = "message";
      const dataLines: string[] = [];
      for (const line of lines) {
        if (line.startsWith("event:")) event = line.slice("event:".length).trim() || "message";
        if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trimStart());
      }
      onEvent(event, dataLines.join("\n"));
    }
  }
};

export const readAiPanelPrefs = (
  storageKeyPrefix: string,
  defaults: AiPanelPrefs,
): AiPanelPrefs => {
  if (typeof window === "undefined") return defaults;

  try {
    const providerRaw = (window.localStorage.getItem(`${storageKeyPrefix}_provider`) || "").trim();
    const model = window.localStorage.getItem(`${storageKeyPrefix}_model`) || defaults.model;
    const modelKey = window.localStorage.getItem(`${storageKeyPrefix}_model_key`) || defaults.modelKey || "";
    const profileId = window.localStorage.getItem(`${storageKeyPrefix}_profile_id`) || defaults.profileId || "";
    const stepsRaw = window.localStorage.getItem(`${storageKeyPrefix}_max_steps`) || "";
    const parsedSteps = Number(stepsRaw);

    const provider: AiProvider =
      providerRaw === "online" || providerRaw === "local" || providerRaw === "ollama" || providerRaw === "codex"
        ? providerRaw
        : defaults.provider;

    return {
      provider,
      model,
      modelKey,
      profileId,
      maxSteps: Number.isFinite(parsedSteps) ? Math.floor(parsedSteps) : defaults.maxSteps,
    };
  } catch {
    return defaults;
  }
};

export const writeAiPanelPrefs = (storageKeyPrefix: string, prefs: AiPanelPrefs) => {
  if (typeof window === "undefined") return;

  try {
    window.localStorage.setItem(`${storageKeyPrefix}_provider`, prefs.provider);
    window.localStorage.setItem(`${storageKeyPrefix}_model`, prefs.model);
    window.localStorage.setItem(`${storageKeyPrefix}_model_key`, prefs.modelKey || "");
    window.localStorage.setItem(`${storageKeyPrefix}_profile_id`, prefs.profileId || "");
    window.localStorage.setItem(`${storageKeyPrefix}_max_steps`, String(prefs.maxSteps));
  } catch {
    // ignore
  }
};
