import { readFileSync, existsSync } from "node:fs";
import { PLUGINS_INDEX_FILE } from "./paths";
import { getWorkspaceRoot } from "./settings";
import { loadMCPConfig } from "./mcp";

/**
 * Read all installed plugin install paths so the Agent SDK exposes their
 * skills + slash commands. Without this the SDK runs with `plugins: []`
 * and `Skill draft-nda` (etc.) fails with "Unknown skill".
 */
export function loadInstalledPlugins(): { type: "local"; path: string }[] {
  if (!existsSync(PLUGINS_INDEX_FILE)) return [];
  try {
    const data = JSON.parse(readFileSync(PLUGINS_INDEX_FILE, "utf8"));
    const out: { type: "local"; path: string }[] = [];
    for (const versions of Object.values(data.plugins || {}) as any[]) {
      for (const v of versions) {
        if (v.installPath && existsSync(v.installPath)) {
          out.push({ type: "local", path: v.installPath });
        }
      }
    }
    return out;
  } catch {
    return [];
  }
}

/** Cached on module load so we don't re-read installed_plugins.json per request. */
export const INSTALLED_PLUGINS = loadInstalledPlugins();

/**
 * Default options factory for `query()` calls. Endpoints can spread this and
 * override what they need (e.g. `resume` for chat continuation).
 */
export function defaultSdkOptions(overrides: Record<string, unknown> = {}) {
  return {
    cwd: getWorkspaceRoot(),
    permissionMode: "bypassPermissions",
    settingSources: ["user", "project", "local"],
    plugins: INSTALLED_PLUGINS,
    skills: "all",
    mcpServers: loadMCPConfig().mcpServers,
    ...overrides,
  };
}
