/**
 * studiograph mcp
 *
 * Starts the Studiograph MCP server for integration with Claude Desktop
 * and other MCP-compatible clients.
 *
 * The server communicates over stdio (JSON-RPC). Claude Desktop spawns this
 * process and communicates directly — no HTTP port is opened.
 *
 * Claude Desktop config (~/.config/Claude/claude_desktop_config.json or
 * ~/Library/Application Support/Claude/claude_desktop_config.json):
 *
 *   {
 *     "mcpServers": {
 *       "studiograph": {
 *         "command": "studiograph",
 *         "args": ["mcp"],
 *         "cwd": "/absolute/path/to/your/workspace"
 *       }
 *     }
 *   }
 *
 * NOTE: Do not use console.log() in this process — stdout is owned by the
 * MCP protocol. Use console.error() for any diagnostic output.
 */
import { Command } from 'commander';
import { resolve } from 'path';
import { realpathSync } from 'fs';
import { Workspace } from '../../core/workspace.js';
import { WorkspaceManager } from '../../core/workspace-manager.js';
import { loadUserConfig } from '../../core/user-config.js';
import { tryResolve } from '../../core/secrets/read-flip.js';
import { AuthService } from '../../services/auth-service.js';
import { resolveStdioUser, createInProcessMcpClient } from '../../mcp/server.js';
import { StdioProxy } from '../../mcp/stdio-proxy.js';
export const mcpCommand = new Command('mcp')
    .description('Start the Studiograph MCP server for Claude Desktop integration')
    .argument('[workspace]', 'Path to workspace (defaults to current directory)')
    .action(async (workspaceArg) => {
    // Canonicalize (absolute + symlinks resolved) so the discovery
    // `workspacePath` match against the running server is exact. The server
    // writes `process.cwd()`, which Node already real-path-resolves; without
    // realpath here a symlinked path (e.g. macOS /tmp → /private/tmp) would
    // mismatch and the proxy would needlessly fall back to a local write.
    const requested = resolve(workspaceArg ?? process.cwd());
    let workspacePath = requested;
    try {
        workspacePath = realpathSync(requested);
    }
    catch {
        /* path may not exist yet — the isWorkspace() check below handles it */
    }
    const workspace = new Workspace(workspacePath);
    if (!workspace.isWorkspace()) {
        process.stderr.write('Not a Studiograph workspace.\n' +
            'Run `studiograph init` first, or pass the workspace path: studiograph mcp /path/to/workspace\n');
        process.exit(1);
    }
    const config = await workspace.loadConfig();
    // Propagate Anthropic API key from store (Phase 6) or user config
    // if not already set. The store wins over user.json — post Phase 6,
    // user.json is no longer authoritative for credentials. The MCP CLI
    // assumes Anthropic since it's the original use case; if you've
    // switched providers, set ANTHROPIC_API_KEY in your shell manually.
    const userConfig = loadUserConfig();
    const apiKey = tryResolve('model.anthropic.api_key') ?? userConfig.api_key;
    if (apiKey && !process.env.ANTHROPIC_API_KEY) {
        process.env.ANTHROPIC_API_KEY = apiKey;
    }
    // MCP uses a service identity for git commits made via create/update tools
    const gitUser = {
        id: 'mcp',
        name: 'Studiograph MCP',
        email: 'noreply@studiograph.local',
    };
    const workspaceManager = new WorkspaceManager(workspacePath, config, gitUser);
    const authService = new AuthService(workspacePath);
    // Resolve identity up front so the proxy fails closed (same message as the
    // old direct stdio server) before opening the stdio transport.
    const user = resolveStdioUser(authService);
    const token = process.env.STUDIOGRAPH_MCP_TOKEN?.trim();
    if (!user || !token) {
        process.stderr.write('Studiograph MCP: STUDIOGRAPH_MCP_TOKEN is required.\n' +
            'Generate a token with:\n' +
            '  curl -X POST http://<host>/api/auth/tokens \\\n' +
            '       -H "Content-Type: application/json" \\\n' +
            '       -b __sg_token=<your-jwt> \\\n' +
            '       -d \'{"name":"claude-desktop"}\'\n' +
            'Then set STUDIOGRAPH_MCP_TOKEN=<token> in your Claude Desktop MCP config env.\n');
        process.exit(1);
    }
    // Audit signal (stderr only — stdout is the JSON-RPC channel). Preserves the
    // identity line the old direct stdio server logged on startup.
    process.stderr.write(`Studiograph MCP: authenticated as ${user.email}\n`);
    // Transparent stdio→HTTP proxy: forward tool calls to the running local
    // server (so writes merge into any open editor) when one is reachable, else
    // fall back to an in-process server (safe: no server ⇒ no live editor).
    const proxy = new StdioProxy({
        workspacePath,
        token,
        buildLocalClient: () => createInProcessMcpClient(workspaceManager, authService, user),
    });
    await proxy.start();
});
//# sourceMappingURL=mcp.js.map