import { resolvePluginEntry } from "./plugin-entry-resolver.js";

/**
 * Canonical plugin id for @remnic/plugin-openclaw.
 *
 * This is the identifier OpenClaw uses as a lookup key in plugins.slots.memory
 * and plugins.entries.<id>. The legacy shim package @joshuaswarren/openclaw-engram
 * intentionally uses a different id ("openclaw-engram") as a backwards-compat alias.
 */
export const PLUGIN_ID = "openclaw-remnic" as const;
export const LEGACY_PLUGIN_ID = "openclaw-engram" as const;

const REMNIC_PLUGIN_IDS = [PLUGIN_ID, LEGACY_PLUGIN_ID] as const;

/**
 * Resolve the Remnic plugin entry from an OpenClaw-shaped config object.
 *
 * Kept as a compatibility subpath for consumers of @remnic/core/plugin-id while
 * the shared resolver lives in plugin-entry-resolver.ts.
 */
export function resolveRemnicPluginEntry(
  raw: unknown,
  preferredId?: string,
): Record<string, unknown> | undefined {
  return resolvePluginEntry(raw, {
    candidateIds: REMNIC_PLUGIN_IDS,
    preferredId,
    getEntries(candidate) {
      const plugins = candidate["plugins"];
      if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) {
        return undefined;
      }
      const entries = (plugins as Record<string, unknown>)["entries"];
      return entries && typeof entries === "object" && !Array.isArray(entries)
        ? (entries as Record<string, unknown>)
        : undefined;
    },
    getSlotId(candidate) {
      const plugins = candidate["plugins"];
      if (!plugins || typeof plugins !== "object" || Array.isArray(plugins)) {
        return undefined;
      }
      const slots = (plugins as Record<string, unknown>)["slots"];
      if (!slots || typeof slots !== "object" || Array.isArray(slots)) {
        return undefined;
      }
      const slotId = (slots as Record<string, unknown>)["memory"];
      return typeof slotId === "string" ? slotId : undefined;
    },
  });
}
