import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import type { ExpertDefinition, ExpertEntryMode, SystemSummary } from "@qjclaw/shared-types";

interface ExpertManifestRecord {
  id: string;
  name: string;
  entryMode: ExpertEntryMode;
  description?: string;
  starterPrompt?: string;
  promptFile?: string;
  projectMatchKeywords?: string[];
}

const EXPERT_PROMPTS_DIR = "expert-prompts";
const EXPERT_MANIFEST_FILE = "manifest.json";

export function resolveExpertPromptsRoot(systemSummary: SystemSummary): string {
  if (systemSummary.isPackaged) {
    return path.join(systemSummary.resourcesPath, EXPERT_PROMPTS_DIR);
  }

  return path.resolve(systemSummary.appPath, "assets", EXPERT_PROMPTS_DIR);
}

export class ExpertCatalogService {
  constructor(private readonly systemSummary: SystemSummary) {}

  list(): ExpertDefinition[] {
    const root = resolveExpertPromptsRoot(this.systemSummary);
    const manifestPath = path.join(root, EXPERT_MANIFEST_FILE);
    if (!existsSync(manifestPath)) {
      return [];
    }

    const payload = JSON.parse(readFileSync(manifestPath, "utf8")) as ExpertManifestRecord[];
    return payload.map((item) => {
      const promptPath = item.promptFile ? path.join(root, item.promptFile) : undefined;
      const promptAvailable = Boolean(item.starterPrompt?.trim()) || Boolean(promptPath && existsSync(promptPath));
      return {
        id: item.id,
        name: item.name,
        entryMode: item.entryMode,
        description: item.description,
        starterPrompt: item.starterPrompt,
        promptFile: item.promptFile,
        promptAvailable,
        projectMatchKeywords: item.projectMatchKeywords ?? []
      } satisfies ExpertDefinition;
    });
  }
}
