import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import type { SystemSummary } from "@qjclaw/shared-types";

const BOOTSTRAP_EXPERT_PROMPT_FILES: Record<string, string> = {
  "content-account-planning": "内容账号规划专家prompt.md",
  zhihu: "知乎专家prompt.md"
};

function normalizeText(content: string): string {
  return content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n").trim();
}

async function pathExists(targetPath: string): Promise<boolean> {
  try {
    await stat(targetPath);
    return true;
  } catch {
    return false;
  }
}

export function resolveBootstrapPromptsRoot(systemSummary: SystemSummary): string {
  if (systemSummary.isPackaged) {
    return path.join(systemSummary.resourcesPath, "bootstrap", "prompts");
  }

  return path.resolve(systemSummary.appPath, "bootstrap", "prompts");
}

export async function loadBootstrapExpertPrompt(systemSummary: SystemSummary, projectId: string): Promise<string | null> {
  const fileName = BOOTSTRAP_EXPERT_PROMPT_FILES[projectId];
  if (!fileName) {
    return null;
  }

  const promptPath = path.join(resolveBootstrapPromptsRoot(systemSummary), fileName);
  if (!(await pathExists(promptPath))) {
    return null;
  }

  const raw = await readFile(promptPath, "utf8");
  const normalized = normalizeText(raw);
  return normalized || null;
}
