// src/adapters/cursor.ts — Cursor MCP installer.
//
// Cursor reads MCP servers from ~/.cursor/mcp.json. The schema mirrors
// Claude Code's mcpServers map (Cursor cribs the protocol), so the entry
// shape is identical.

import * as path from "path";
import {
  AdapterContext,
  AdapterResult,
  PlatformAdapter,
  SERVER_KEY,
} from "./types";
import {
  homeDir,
  readJsonOrEmpty,
  serverEntry,
  spliceServer,
  writeJsonAtomic,
} from "./util";

export class CursorAdapter implements PlatformAdapter {
  readonly id = "cursor";

  install(ctx: AdapterContext): AdapterResult {
    const configPath = path.join(homeDir(ctx.homeOverride), ".cursor", "mcp.json");

    if (ctx.dryRun) {
      return {
        platform: this.id,
        configPath,
        ok: true,
        detail: `would register ${SERVER_KEY} -> ${ctx.serverPath} in ${configPath}`,
      };
    }

    try {
      const config = readJsonOrEmpty(configPath);
      spliceServer(config, "mcpServers", SERVER_KEY, serverEntry(ctx.serverPath));
      writeJsonAtomic(configPath, config);
      return {
        platform: this.id,
        configPath,
        ok: true,
        detail: `registered ${SERVER_KEY} in ${configPath}`,
      };
    } catch (err) {
      return {
        platform: this.id,
        configPath,
        ok: false,
        detail: `failed: ${err instanceof Error ? err.message : String(err)}`,
      };
    }
  }
}
