import { promises as fs } from "fs";
import path from "path";

export type LocalAiConfig = {
  baseUrl: string; // 形如 http(s)://host/v1
  apiKey: string;
  model: string;
};

const tryReadText = async (file: string) => {
  try {
    return await fs.readFile(file, "utf8");
  } catch {
    return null;
  }
};

const findConfigText = async () => {
  const cwd = process.cwd();
  const candidates = [
    path.join(cwd, "ai.local.md"),
    path.join(cwd, "ai-local.md"),
    path.join(cwd, "..", "ai.local.md"),
    path.join(cwd, "..", "ai-local.md"),
    path.join(cwd, "..", "..", "ai.local.md"),
    path.join(cwd, "..", "..", "ai-local.md"),
  ];
  for (const f of candidates) {
    const text = await tryReadText(f);
    if (text) return text;
  }
  return null;
};

const parseAiMd = (raw: string): LocalAiConfig | null => {
  const lines = raw
    .split(/\r?\n/)
    .map((l) => l.trim())
    .filter(Boolean);

  // 兼容格式：
  // apikey：xxxx（可选）
  // http://.../v1
  // model-name
  const apiLine = lines.find((l) => /^apikey[:：]/i.test(l));
  const apiKey = apiLine ? apiLine.replace(/^apikey[:：]\s*/i, "").trim() : "";
  const baseUrl = lines.find((l) => /^https?:\/\//i.test(l)) ?? "";
  const model =
    (lines.findLast?.((l) => !/^apikey[:：]/i.test(l) && !/^https?:\/\//i.test(l)) ??
      lines.find((l) => !/^apikey[:：]/i.test(l) && !/^https?:\/\//i.test(l)) ??
      "").trim();

  if (!baseUrl || !model) return null;
  return {
    apiKey,
    baseUrl: baseUrl.replace(/\/+$/, ""),
    model,
  };
};

export const loadLocalAiConfig = async (): Promise<LocalAiConfig | null> => {
  // 环境变量优先（方便部署），其次读取 ai.local.md / ai-local.md
  const envBase = (process.env.LOCAL_AI_BASE_URL ?? "").trim();
  const envModel = (process.env.LOCAL_AI_MODEL ?? "").trim();
  const envKey = (process.env.LOCAL_AI_API_KEY ?? "").trim();
  if (envBase && envModel) {
    return {
      baseUrl: envBase.replace(/\/+$/, ""),
      apiKey: envKey,
      model: envModel,
    };
  }

  const text = await findConfigText();
  if (!text) return null;
  return parseAiMd(text);
};

