import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { ClaudeCodeIntegration } from './integration.js';
import { ClaudeCodeConfig, ProjectContext, CodeAssistRequest } from './types.js';
import { promises as fs } from 'fs';
import path from 'path';

let configManager: ConfigManager;
let claudeCodeIntegration: ClaudeCodeIntegration;

export async function setupClaudeCodeIntegration(server: Server, config?: ConfigManager) {
  configManager = config || new ConfigManager();
  claudeCodeIntegration = new ClaudeCodeIntegration(configManager);

  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (!args) {
      throw new Error('No arguments provided');
    }

    switch (name) {
      case 'setup_claude_code_integration': {
        const {
          enableContextSharing = true,
          enableAutoDocumentation = true,
          enableCodeSuggestions = true,
          enableProjectMemory = true,
          createCLAUDEmd = true,
          backupExisting = true,
        } = args as {
          enableContextSharing?: boolean;
          enableAutoDocumentation?: boolean;
          enableCodeSuggestions?: boolean;
          enableProjectMemory?: boolean;
          createCLAUDEmd?: boolean;
          backupExisting?: boolean;
        };

        try {
          // Check for existing CLAUDE.md and handle appropriately
          const existingCLAUDEmd = await claudeCodeIntegration.checkExistingCLAUDEmd();
          
          const config: ClaudeCodeConfig = {
            enableContextSharing,
            enableAutoDocumentation,
            enableCodeSuggestions,
            enableProjectMemory,
            createCLAUDEmd,
          };

          const setupResult = await claudeCodeIntegration.setupIntegration(config, { backupExisting });

          return {
            content: [
              {
                type: 'text',
                text: `✅ Claude Code integration configured!

${existingCLAUDEmd.exists ? `📋 Existing CLAUDE.md handling:
• Status: ${existingCLAUDEmd.wasAtlasManaged ? 'Updated Atlas sections' : 'Preserved your content, added Atlas sections'}
${existingCLAUDEmd.backupCreated ? `• Backup: ${existingCLAUDEmd.backupPath}` : ''}

` : ''}🤖 Features enabled:
• Context sharing: ${enableContextSharing ? '✅' : '❌'}
• Auto-documentation: ${enableAutoDocumentation ? '✅' : '❌'}
• Code suggestions: ${enableCodeSuggestions ? '✅' : '❌'}
• Project memory: ${enableProjectMemory ? '✅' : '❌'}
• CLAUDE.md ${existingCLAUDEmd.exists ? 'enhanced' : 'created'}: ${createCLAUDEmd ? '✅' : '❌'}

📄 Files ${existingCLAUDEmd.exists ? 'updated' : 'created'}:
${setupResult.filesCreated.map(file => `• ${file}`).join('\n')}

💡 Claude Code will now have enhanced context about:
• Your project structure and conventions
• Active development workflows (TDD, Git flow)
• Documentation standards and templates
• Atlas MCP capabilities and current project state

🚀 Try these Claude Code commands:
• Ask about project status: "What's the current state of this project?"
• Request code with context: "Create a new feature following our TDD workflow"
• Get documentation help: "Generate API docs for this module"`,
              },
            ],
            structured: {
              config,
              filesCreated: setupResult.filesCreated,
              features: setupResult.enabledFeatures,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error setting up Claude Code integration: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'generate_project_context': {
        const {
          includeStructure = true,
          includeWorkflows = true,
          includeConventions = true,
          includeProgress = true,
        } = args as {
          includeStructure?: boolean;
          includeWorkflows?: boolean;
          includeConventions?: boolean;
          includeProgress?: boolean;
        };

        try {
          const context = await claudeCodeIntegration.generateProjectContext({
            includeStructure,
            includeWorkflows,
            includeConventions,
            includeProgress,
          });

          // Save context to CLAUDE.md
          const claudeMdPath = path.join(process.cwd(), 'CLAUDE.md');
          await fs.writeFile(claudeMdPath, context.markdown);

          return {
            content: [
              {
                type: 'text',
                text: `✅ Project context generated and saved to CLAUDE.md!

📊 Context includes:
• Project structure: ${includeStructure ? '✅' : '❌'}
• Development workflows: ${includeWorkflows ? '✅' : '❌'}
• Code conventions: ${includeConventions ? '✅' : '❌'}
• Current progress: ${includeProgress ? '✅' : '❌'}

📄 CLAUDE.md updated with:
• Project overview and architecture
• Development workflows and TDD practices
• Available Atlas MCP tools
• Code style and conventions
• Current project status and next steps

💡 Claude Code can now understand your project context automatically!`,
              },
            ],
            structured: {
              contextGenerated: true,
              filePath: 'CLAUDE.md',
              sections: context.sections,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error generating project context: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'create_claude_code_workflow': {
        const {
          workflowType,
          description,
          steps = [],
          tools = [],
        } = args as {
          workflowType: string;
          description: string;
          steps?: string[];
          tools?: string[];
        };

        try {
          const workflow = await claudeCodeIntegration.createWorkflow({
            workflowType,
            description,
            steps,
            tools,
          });

          // Add workflow to CLAUDE.md
          await claudeCodeIntegration.addWorkflowToCLAUDEmd(workflow);

          return {
            content: [
              {
                type: 'text',
                text: `✅ Claude Code workflow created!

📋 Workflow: ${workflowType}
📝 Description: ${description}

🔄 Steps (${workflow.steps.length}):
${workflow.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}

🛠️ Tools used:
${workflow.tools.map(tool => `• ${tool}`).join('\n')}

📄 Workflow added to CLAUDE.md for Claude Code reference.

💡 You can now ask Claude Code to "follow the ${workflowType} workflow" for consistent development patterns.`,
              },
            ],
            structured: {
              workflow,
              addedToCLAUDEmd: true,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error creating workflow: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'sync_claude_code_context': {
        try {
          const syncResult = await claudeCodeIntegration.syncContext();

          return {
            content: [
              {
                type: 'text',
                text: `🔄 Claude Code context synchronized!

📊 Updated information:
• Project structure: ${syncResult.structureUpdated ? '✅' : '⏭️'}
• Active tasks: ${syncResult.tasksUpdated ? '✅' : '⏭️'}
• Code conventions: ${syncResult.conventionsUpdated ? '✅' : '⏭️'}
• Documentation: ${syncResult.docsUpdated ? '✅' : '⏭️'}

📄 Files updated:
${syncResult.filesUpdated.map(file => `• ${file}`).join('\n')}

⏰ Last sync: ${new Date().toISOString()}

💡 Claude Code now has the latest project state and can provide more accurate assistance.`,
              },
            ],
            structured: {
              syncResult,
              timestamp: new Date().toISOString(),
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error syncing context: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'backup_claude_md': {
        try {
          const backupResult = await claudeCodeIntegration.createBackup();
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ CLAUDE.md backup created!

📄 Original: CLAUDE.md
💾 Backup: ${backupResult.backupPath}
🕐 Created: ${backupResult.timestamp}

Your original CLAUDE.md has been safely backed up. You can now run setup_claude_code_integration to enhance it with Atlas features.`,
              },
            ],
            structured: {
              backupCreated: true,
              originalPath: 'CLAUDE.md',
              backupPath: backupResult.backupPath,
              timestamp: backupResult.timestamp,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error creating backup: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'restore_claude_md': {
        const { backupPath } = args as { backupPath?: string };
        
        try {
          const restoreResult = await claudeCodeIntegration.restoreFromBackup(backupPath);
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ CLAUDE.md restored from backup!

💾 Backup used: ${restoreResult.backupPath}
📄 Restored to: CLAUDE.md
🕐 Restored at: ${restoreResult.timestamp}

Your original CLAUDE.md has been restored. Atlas sections have been removed.`,
              },
            ],
            structured: {
              restored: true,
              backupPath: restoreResult.backupPath,
              timestamp: restoreResult.timestamp,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error restoring backup: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'get_claude_code_suggestions': {
        const {
          requestType = 'general',
          context = '',
          currentFile = '',
        } = args as {
          requestType?: 'general' | 'refactor' | 'feature' | 'documentation' | 'debugging' | 'testing';
          context?: string;
          currentFile?: string;
        };

        try {
          const suggestions = await claudeCodeIntegration.generateSuggestions({
            requestType,
            context,
            currentFile,
          });

          return {
            content: [
              {
                type: 'text',
                text: `💡 Claude Code Suggestions

🎯 Request type: ${requestType}
${currentFile ? `📄 Current file: ${currentFile}` : ''}

📋 Suggestions:
${suggestions.map((suggestion, i) => `${i + 1}. **${suggestion.title}**\n   ${suggestion.description}\n   ${suggestion.command ? `   Command: \`${suggestion.command}\`` : ''}`).join('\n\n')}

💡 These suggestions are tailored to your project's current state and Atlas MCP configuration.`,
              },
            ],
            structured: {
              requestType,
              currentFile,
              suggestions,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error getting suggestions: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      default:
        return null as any;
    }
  });

  return {
    tools: [
      {
        name: 'setup_claude_code_integration',
        description: 'Configure seamless integration with Claude Code for enhanced development experience',
        inputSchema: {
          type: 'object',
          properties: {
            enableContextSharing: {
              type: 'boolean',
              default: true,
              description: 'Share project context with Claude Code automatically'
            },
            enableAutoDocumentation: {
              type: 'boolean',
              default: true,
              description: 'Auto-generate and maintain CLAUDE.md with project info'
            },
            enableCodeSuggestions: {
              type: 'boolean',
              default: true,
              description: 'Enable context-aware code suggestions'
            },
            enableProjectMemory: {
              type: 'boolean',
              default: true,
              description: 'Maintain project memory for better assistance'
            },
            createCLAUDEmd: {
              type: 'boolean',
              default: true,
              description: 'Create/update CLAUDE.md with comprehensive project info'
            },
            backupExisting: {
              type: 'boolean',
              default: true,
              description: 'Create backup of existing CLAUDE.md before modifying'
            },
          },
          required: []
        },
      },
      {
        name: 'generate_project_context',
        description: 'Generate comprehensive project context for Claude Code',
        inputSchema: {
          type: 'object',
          properties: {
            includeStructure: {
              type: 'boolean',
              default: true,
              description: 'Include project structure and architecture'
            },
            includeWorkflows: {
              type: 'boolean',
              default: true,
              description: 'Include development workflows and TDD practices'
            },
            includeConventions: {
              type: 'boolean',
              default: true,
              description: 'Include code conventions and style guides'
            },
            includeProgress: {
              type: 'boolean',
              default: true,
              description: 'Include current progress and next steps'
            },
          },
          required: []
        },
      },
      {
        name: 'create_claude_code_workflow',
        description: 'Create a documented workflow for Claude Code to follow',
        inputSchema: {
          type: 'object',
          properties: {
            workflowType: {
              type: 'string',
              description: 'Type of workflow (e.g., "feature-development", "bug-fix", "refactor")'
            },
            description: {
              type: 'string',
              description: 'Description of the workflow'
            },
            steps: {
              type: 'array',
              items: { type: 'string' },
              description: 'Step-by-step workflow instructions'
            },
            tools: {
              type: 'array',
              items: { type: 'string' },
              description: 'Atlas MCP tools used in this workflow'
            },
          },
          required: ['workflowType', 'description'],
        },
      },
      {
        name: 'backup_claude_md',
        description: 'Create a backup of existing CLAUDE.md before Atlas modifications',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        },
      },
      {
        name: 'restore_claude_md',
        description: 'Restore CLAUDE.md from a backup, removing Atlas sections',
        inputSchema: {
          type: 'object',
          properties: {
            backupPath: {
              type: 'string',
              description: 'Path to backup file (optional - will find latest if not specified)'
            },
          },
          required: []
        },
      },
      {
        name: 'sync_claude_code_context',
        description: 'Synchronize current project state with Claude Code context',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        },
      },
      {
        name: 'get_claude_code_suggestions',
        description: 'Get context-aware suggestions for Claude Code interactions',
        inputSchema: {
          type: 'object',
          properties: {
            requestType: {
              type: 'string',
              enum: ['general', 'debugging', 'feature', 'refactor', 'documentation', 'testing'],
              default: 'general',
              description: 'Type of assistance needed'
            },
            context: {
              type: 'string',
              description: 'Additional context about what you\'re working on'
            },
            currentFile: {
              type: 'string',
              description: 'Current file being worked on (optional)'
            },
          },
          required: []
        },
      },
    ],
    resources: [
      {
        uri: 'claude-code://project/context',
        name: 'Project Context for Claude Code',
        description: 'Comprehensive project context optimized for Claude Code',
        mimeType: 'text/markdown',
      },
      {
        uri: 'claude-code://workflows/all',
        name: 'Claude Code Workflows',
        description: 'All available workflows for Claude Code to follow',
        mimeType: 'application/json',
      },
    ],
  };
}