// mcp_json.dart — Builds .cursor/mcp.json from project brief (env placeholders only).

import 'dart:convert';

import 'models.dart';

class McpJsonBuilder {
  /// JSON string for Cursor MCP config. Never embed secrets — use `\${VAR}` in strings.
  static String build(ProjectBrief brief) {
    if (brief.mcpPreset == 'minimal') {
      return const JsonEncoder.withIndent('  ')
          .convert(<String, dynamic>{'mcpServers': <String, dynamic>{}});
    }

    final servers = <String, Map<String, dynamic>>{
      'filesystem': {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-filesystem', '.'],
        'description': 'Read/write project files under the workspace root',
      },
      'flutter-docs': {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-fetch'],
        'env': {'BASE_URL': 'https://api.flutter.dev/flutter'},
        'description': 'Flutter API documentation lookup',
      },
      'dart-pub': {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-fetch'],
        'env': {'BASE_URL': 'https://pub.dev/api'},
        'description': 'Pub.dev package metadata and versions',
      },
      'github': {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-github'],
        'env': {'GITHUB_TOKEN': r'${GITHUB_TOKEN}'},
        'description': 'GitHub issues and PR context (requires GITHUB_TOKEN)',
      },
    };

    if (brief.backends.contains('firebase')) {
      servers['firebase'] = {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-firebase'],
        'env': {'FIREBASE_PROJECT': r'${FIREBASE_PROJECT_ID}'},
        'description':
            'Firebase project context (configure FIREBASE_PROJECT_ID)',
      };
    }

    if (brief.designSource == 'figma_mcp') {
      servers['figma'] = {
        'url': 'https://mcp.figma.com/mcp',
        'type': 'http',
        'headers': {
          'Authorization': r'Bearer ${FIGMA_ACCESS_TOKEN}',
        },
        'description':
            'Figma MCP — set FIGMA_ACCESS_TOKEN (never commit the value)',
      };
    }

    if (brief.backends.contains('supabase')) {
      servers['supabase'] = {
        'command': 'npx',
        'args': ['-y', '@supabase/mcp-server-supabase@latest'],
        'env': {
          'SUPABASE_ACCESS_TOKEN': r'${SUPABASE_ACCESS_TOKEN}',
        },
        'description': 'Supabase MCP — token from env only',
      };
    }

    if (brief.apiDocsFormat == 'openapi' && brief.apiDocsPath.isNotEmpty) {
      servers['openapi-ref'] = {
        'command': 'npx',
        'args': ['-y', '@modelcontextprotocol/server-fetch'],
        'env': {
          'OPENAPI_SPEC_URL': r'${OPENAPI_SPEC_URL}',
        },
        'description':
            'Optional fetch MCP — point OPENAPI_SPEC_URL at a hosted spec or file:// URL you expose locally',
      };
    }

    return const JsonEncoder.withIndent('  ').convert({'mcpServers': servers});
  }
}
