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

export type OnlineAiConfig = {
  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.md"),
    path.join(cwd, "..", "ai.md"),
    path.join(cwd, "..", "..", "ai.md"),
  ];
  for (const f of candidates) {
    const text = await tryReadText(f);
    if (text) return text;
  }
  return null;
};

const parseAiMd = (raw: string): OnlineAiConfig | 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)) ?? "";
  // model 行通常是最后一行
  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 (!apiKey || !baseUrl || !model) return null;

  // Cloudflare 场景下 http 可能只允许 GET（/models），但 POST（/chat/completions）会被拦截；
  // 对非本机地址默认升级到 https，确保在线推理可用。
  let normalizedBaseUrl = baseUrl.replace(/\/+$/, "");
  try {
    const u = new URL(normalizedBaseUrl);
    if (u.protocol === "http:" && u.hostname !== "127.0.0.1" && u.hostname !== "localhost") {
      u.protocol = "https:";
      normalizedBaseUrl = u.toString().replace(/\/+$/, "");
    }
  } catch {
    // ignore
  }

  return {
    apiKey,
    baseUrl: normalizedBaseUrl,
    model,
  };
};

export const loadOnlineAiConfig = async (): Promise<OnlineAiConfig | null> => {
  // 环境变量优先（方便生产/部署），其次读取 ai.md（本地开发快捷配置）
  const envKey = (process.env.ONLINE_AI_API_KEY ?? "").trim();
  const envBase = (process.env.ONLINE_AI_BASE_URL ?? "").trim();
  const envModel = (process.env.ONLINE_AI_MODEL ?? "").trim();
  if (envKey && envBase && envModel) {
    // 同 parseAiMd：默认把非本机 http 升级为 https
    let normalizedBaseUrl = envBase.replace(/\/+$/, "");
    try {
      const u = new URL(normalizedBaseUrl);
      if (u.protocol === "http:" && u.hostname !== "127.0.0.1" && u.hostname !== "localhost") {
        u.protocol = "https:";
        normalizedBaseUrl = u.toString().replace(/\/+$/, "");
      }
    } catch {
      // ignore
    }
    return { apiKey: envKey, baseUrl: normalizedBaseUrl, model: envModel };
  }

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