import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { DeprecationManager } from './deprecation-manager.js';

let configManager: ConfigManager;
let deprecationManager: DeprecationManager;

export async function setupDeprecationTools(server: Server, config?: ConfigManager) {
  configManager = config || new ConfigManager();
  deprecationManager = new DeprecationManager(configManager);
  await deprecationManager.init();

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

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

    switch (name) {
      case 'mark_deprecated': {
        const {
          objectType,
          objectId,
          objectPath,
          reason,
          deprecatedBy,
          upgradeInstructions,
          alternativeId,
          alternativePath
        } = args as any;

        try {
          const notice = await deprecationManager.markAsDeprecated({
            objectType,
            objectId,
            objectPath,
            reason,
            deprecatedBy,
            upgradeInstructions,
            alternativeId,
            alternativePath
          });

          return {
            content: [
              {
                type: 'text',
                text: `⚠️ Object marked as deprecated!

📋 **Deprecation Notice**
- **ID**: ${notice.id}
- **Type**: ${notice.objectType}
- **Object**: ${notice.objectId}
- **Reason**: ${notice.reason}

📝 **Upgrade Instructions**:
${notice.upgradeInstructions}

${notice.alternativeId ? `✨ **Alternative**: ${notice.alternativeId}` : ''}

💡 To create an upgrade plan, run:
\`deprecation_plan objectIds=["${notice.objectId}"]\``
              }
            ],
            structured: {
              notice,
              deprecated: true
            }
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Failed to mark as deprecated: ${(error as Error).message}`
              }
            ]
          };
        }
      }

      case 'deprecation_plan': {
        const { objectIds } = args as { objectIds: string[] };

        try {
          const plan = await deprecationManager.createDeprecationPlan(objectIds);

          return {
            content: [
              {
                type: 'text',
                text: `📋 Deprecation Upgrade Plan

**Objects to Upgrade**: ${plan.affectedObjects.length}
**Impact Level**: ${plan.estimatedImpact.toUpperCase()}
**User Approval Required**: ${plan.requiresUserApproval ? '✅ Yes' : '❌ No'}

## Affected Objects:
${plan.affectedObjects.map(obj => 
  `- ${obj.type} "${obj.id}" → ${obj.proposedAction}`
).join('\n')}

## Upgrade Steps (${plan.upgradeSteps.length}):
${plan.upgradeSteps.map(step => 
  `${step.order}. ${step.description} (${step.estimatedDuration})
   - Automated: ${step.automated ? '✅' : '❌'}
   - Reversible: ${step.reversible ? '✅' : '❌'}`
).join('\n\n')}

⚠️ **IMPORTANT**: Review this plan carefully before execution.

To execute this upgrade:
\`execute_deprecation_upgrade plan={...} userApproval=true\``
              }
            ],
            structured: {
              plan,
              requiresApproval: plan.requiresUserApproval
            }
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Failed to create plan: ${(error as Error).message}`
              }
            ]
          };
        }
      }

      case 'check_deprecations': {
        const { objectType } = args as { objectType?: string };

        try {
          const deprecations = await deprecationManager.checkDeprecations(objectType);

          if (deprecations.length === 0) {
            return {
              content: [
                {
                  type: 'text',
                  text: '✅ No deprecated objects found!'
                }
              ]
            };
          }

          return {
            content: [
              {
                type: 'text',
                text: `⚠️ Found ${deprecations.length} deprecated object(s)

${deprecations.map(dep => `
📦 **${dep.objectType}** - ${dep.objectId}
- Deprecated: ${new Date(dep.deprecatedAt).toLocaleDateString()}
- Reason: ${dep.reason}
- Alternative: ${dep.alternativeId || 'None specified'}
`).join('\n---\n')}

💡 Create upgrade plans with:
\`deprecation_plan objectIds=${JSON.stringify(deprecations.map(d => d.objectId))}\``
              }
            ],
            structured: {
              deprecations,
              count: deprecations.length
            }
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Failed to check deprecations: ${(error as Error).message}`
              }
            ]
          };
        }
      }

      default:
        return null as any;
    }
  });

  return {
    tools: [
      {
        name: 'mark_deprecated',
        description: 'Mark an object as deprecated with upgrade instructions',
        inputSchema: {
          type: 'object',
          properties: {
            objectType: {
              type: 'string',
              enum: ['board', 'task', 'memory', 'sprint', 'epic', 'config', 'other'],
              description: 'Type of object being deprecated'
            },
            objectId: {
              type: 'string',
              description: 'Unique identifier of the object'
            },
            objectPath: {
              type: 'string',
              description: 'File path or location of the object'
            },
            reason: {
              type: 'string',
              description: 'Reason for deprecation'
            },
            deprecatedBy: {
              type: 'string',
              description: 'Who is deprecating this (user/system)'
            },
            upgradeInstructions: {
              type: 'string',
              description: 'Instructions for upgrading or migrating'
            },
            alternativeId: {
              type: 'string',
              description: 'ID of the replacement object'
            },
            alternativePath: {
              type: 'string',
              description: 'Path to the replacement object'
            }
          },
          required: ['objectType', 'objectId', 'reason', 'deprecatedBy', 'upgradeInstructions']
        }
      },
      {
        name: 'deprecation_plan',
        description: 'Create an upgrade plan for deprecated objects',
        inputSchema: {
          type: 'object',
          properties: {
            objectIds: {
              type: 'array',
              items: { type: 'string' },
              description: 'IDs of deprecated objects to include in plan'
            }
          },
          required: ['objectIds']
        }
      },
      {
        name: 'check_deprecations',
        description: 'Check for deprecated objects in the project',
        inputSchema: {
          type: 'object',
          properties: {
            objectType: {
              type: 'string',
              enum: ['board', 'task', 'memory', 'sprint', 'epic', 'config', 'other'],
              description: 'Filter by object type'
            }
          },
          required: []
        }
      }
    ],
    resources: []
  };
}