import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { RoadmapManager } from './roadmap-manager.js';
import { PrioritizationEngine } from './prioritization-engine.js';
import { TimelineGenerator } from './timeline-generator.js';
import { RoadmapWizard } from './roadmap-wizard.js';
import { ConfigManager } from '../../config/config-manager.js';
import {
  ProductRoadmap,
  RoadmapTheme,
  Initiative,
  Feature,
  Milestone,
  Release,
  CreateRoadmapOptions,
  AddThemeOptions,
  CreateInitiativeOptions,
  AddFeatureOptions,
  PrioritizationCriteria,
  PrioritizationResult,
  TimelineView,
  RoadmapMetrics,
  ReviewDecision,
  ReviewFeedback,
  RoadmapReview
} from './types.js';

export async function setupProductRoadmap(server: Server, configManager: ConfigManager) {
  const roadmapManager = new RoadmapManager(configManager);
  const prioritizationEngine = new PrioritizationEngine();
  const timelineGenerator = new TimelineGenerator();
  const roadmapWizard = new RoadmapWizard(roadmapManager, prioritizationEngine);
  
  await roadmapManager.initialize();

  return {
    tools: [
      {
        name: 'create_roadmap',
        description: 'Create a new product roadmap with vision and strategic timeline',
        inputSchema: {
          type: 'object',
          properties: {
            name: { type: 'string', description: 'Name of the product roadmap' },
            vision: { type: 'string', description: 'Product vision statement' },
            timeHorizon: { 
              type: 'string', 
              enum: ['quarterly', 'annual', 'multi-year'],
              description: 'Planning time horizon' 
            },
            owner: { type: 'string', description: 'Product owner name' },
            stakeholders: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of stakeholder names'
            }
          },
          required: ['name', 'vision', 'timeHorizon', 'owner']
        }
      },
      {
        name: 'add_roadmap_theme',
        description: 'Add a strategic theme to a product roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            name: { type: 'string', description: 'Theme name' },
            description: { type: 'string', description: 'Theme description' },
            objectives: {
              type: 'array',
              items: { type: 'string' },
              description: 'Strategic objectives'
            },
            priority: {
              type: 'string',
              enum: ['must-have', 'should-have', 'nice-to-have'],
              description: 'Theme priority'
            },
            startQuarter: { type: 'string', description: 'Start quarter (e.g., Q1 2024)' },
            endQuarter: { type: 'string', description: 'End quarter' }
          },
          required: ['roadmapId', 'name', 'description', 'objectives', 'priority', 'startQuarter', 'endQuarter']
        }
      },
      {
        name: 'create_initiative',
        description: 'Create a product initiative within a theme',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            themeId: { type: 'string', description: 'ID of the theme' },
            title: { type: 'string', description: 'Initiative title' },
            description: { type: 'string', description: 'Initiative description' },
            estimatedValue: {
              type: 'object',
              properties: {
                userImpact: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
                revenueImpact: { type: 'number', description: 'Estimated revenue impact' },
                costSavings: { type: 'number', description: 'Estimated cost savings' },
                strategicValue: { type: 'number', description: 'Strategic value (1-10)' },
                customerSatisfaction: { type: 'number', description: 'Projected NPS impact' }
              },
              required: ['userImpact', 'revenueImpact', 'costSavings', 'strategicValue', 'customerSatisfaction']
            },
            estimatedEffort: {
              type: 'object',
              properties: {
                developmentWeeks: { type: 'number' },
                designWeeks: { type: 'number' },
                qaWeeks: { type: 'number' },
                confidence: { type: 'string', enum: ['low', 'medium', 'high'] }
              },
              required: ['developmentWeeks', 'designWeeks', 'qaWeeks', 'confidence']
            },
            risks: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  description: { type: 'string' },
                  likelihood: { type: 'string', enum: ['low', 'medium', 'high'] },
                  impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                  mitigation: { type: 'string' }
                },
                required: ['description', 'likelihood', 'impact', 'mitigation']
              }
            }
          },
          required: ['roadmapId', 'themeId', 'title', 'description', 'estimatedValue', 'estimatedEffort']
        }
      },
      {
        name: 'add_feature',
        description: 'Add a feature to an initiative',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            initiativeId: { type: 'string', description: 'ID of the initiative' },
            name: { type: 'string', description: 'Feature name' },
            description: { type: 'string', description: 'Feature description' },
            businessValue: {
              type: 'object',
              properties: {
                score: { type: 'number', description: 'Business value score (1-100)' },
                rationale: { type: 'string', description: 'Value rationale' },
                metrics: {
                  type: 'array',
                  items: { type: 'string' },
                  description: 'Success metrics'
                }
              },
              required: ['score', 'rationale', 'metrics']
            },
            technicalComplexity: {
              type: 'string',
              enum: ['low', 'medium', 'high', 'very-high'],
              description: 'Technical complexity'
            },
            targetRelease: { type: 'string', description: 'Target release ID (optional)' }
          },
          required: ['roadmapId', 'initiativeId', 'name', 'description', 'businessValue', 'technicalComplexity']
        }
      },
      {
        name: 'prioritize_features',
        description: 'Prioritize features using various methods (RICE, MoSCoW, Value-Effort, etc.)',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            method: {
              type: 'string',
              enum: ['rice', 'value-effort', 'moscow', 'kano', 'custom'],
              description: 'Prioritization method'
            },
            weights: {
              type: 'object',
              properties: {
                businessValue: { type: 'number' },
                userImpact: { type: 'number' },
                strategicAlignment: { type: 'number' },
                technicalFeasibility: { type: 'number' },
                risk: { type: 'number' }
              },
              description: 'Custom weights (only for custom method)'
            },
            scope: {
              type: 'string',
              enum: ['all', 'theme', 'initiative', 'unscheduled'],
              description: 'Scope of prioritization'
            },
            scopeId: { type: 'string', description: 'ID of theme/initiative if scope is specific' }
          },
          required: ['roadmapId', 'method']
        }
      },
      {
        name: 'generate_roadmap_timeline',
        description: 'Generate timeline views of the roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            viewType: {
              type: 'string',
              enum: ['quarterly', 'monthly', 'release', 'now-next-later'],
              description: 'Type of timeline view'
            },
            startPeriod: { type: 'string', description: 'Start quarter/month (for quarterly/monthly views)' },
            endPeriod: { type: 'string', description: 'End quarter/month (for quarterly view)' },
            months: { type: 'number', description: 'Number of months (for monthly view)' }
          },
          required: ['roadmapId', 'viewType']
        }
      },
      {
        name: 'create_milestone',
        description: 'Create a milestone in the roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            name: { type: 'string', description: 'Milestone name' },
            date: { type: 'string', description: 'Milestone date (ISO format)' },
            type: {
              type: 'string',
              enum: ['release', 'business', 'technical', 'regulatory'],
              description: 'Type of milestone'
            },
            description: { type: 'string', description: 'Milestone description' },
            deliverables: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of deliverables'
            },
            dependencies: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of dependency IDs'
            }
          },
          required: ['roadmapId', 'name', 'date', 'type', 'description', 'deliverables']
        }
      },
      {
        name: 'plan_release',
        description: 'Plan a product release',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            version: { type: 'string', description: 'Release version' },
            name: { type: 'string', description: 'Release name' },
            date: { type: 'string', description: 'Release date (ISO format)' },
            features: {
              type: 'array',
              items: { type: 'string' },
              description: 'Feature IDs to include'
            },
            themes: {
              type: 'array',
              items: { type: 'string' },
              description: 'Theme IDs addressed'
            },
            goals: {
              type: 'array',
              items: { type: 'string' },
              description: 'Release goals'
            },
            notes: { type: 'string', description: 'Release notes' }
          },
          required: ['roadmapId', 'version', 'name', 'date', 'features', 'goals']
        }
      },
      {
        name: 'update_feature_status',
        description: 'Update the status of a feature',
        inputSchema: {
          type: 'object',
          properties: {
            featureId: { type: 'string', description: 'ID of the feature' },
            status: {
              type: 'string',
              enum: ['proposed', 'approved', 'in-progress', 'completed', 'cancelled'],
              description: 'New status'
            }
          },
          required: ['featureId', 'status']
        }
      },
      {
        name: 'update_initiative_status',
        description: 'Update the status of an initiative',
        inputSchema: {
          type: 'object',
          properties: {
            initiativeId: { type: 'string', description: 'ID of the initiative' },
            status: {
              type: 'string',
              enum: ['ideation', 'validated', 'scheduled', 'in-development', 'launched'],
              description: 'New status'
            }
          },
          required: ['initiativeId', 'status']
        }
      },
      {
        name: 'get_roadmap_health',
        description: 'Get health assessment and metrics for a roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' }
          },
          required: ['roadmapId']
        }
      },
      {
        name: 'list_roadmaps',
        description: 'List all product roadmaps',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        }
      },
      {
        name: 'get_roadmap',
        description: 'Get detailed information about a specific roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' }
          },
          required: ['roadmapId']
        }
      },
      {
        name: 'get_theme_details',
        description: 'Get detailed information about a theme including initiatives and features',
        inputSchema: {
          type: 'object',
          properties: {
            themeId: { type: 'string', description: 'ID of the theme' }
          },
          required: ['themeId']
        }
      },
      {
        name: 'start_roadmap_wizard',
        description: 'Start an interactive wizard to create a comprehensive product roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Unique session ID for the wizard' }
          },
          required: ['sessionId']
        }
      },
      {
        name: 'continue_roadmap_wizard',
        description: 'Continue the roadmap creation wizard with user input',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Session ID for the wizard' },
            input: { type: 'object', description: 'User input for the current step' }
          },
          required: ['sessionId', 'input']
        }
      },
      {
        name: 'create_initiative_wizard',
        description: 'Start an interactive wizard to create an initiative within a theme',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Unique session ID for the wizard' },
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            themeId: { type: 'string', description: 'ID of the theme' }
          },
          required: ['sessionId', 'roadmapId', 'themeId']
        }
      },
      {
        name: 'continue_initiative_wizard',
        description: 'Continue the initiative creation wizard with user input',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Session ID for the wizard' },
            input: { type: 'object', description: 'User input for the current step' }
          },
          required: ['sessionId', 'input']
        }
      }
    ]
  };
  
  // Tool handlers
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

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

    switch (name) {
      case 'create_roadmap': {
        const params = args as unknown as CreateRoadmapOptions;
        const roadmap = await roadmapManager.createRoadmap(params);
        
        return {
          content: [{
            type: 'text',
            text: `✅ Product roadmap "${roadmap.name}" created successfully!

**Vision**: ${roadmap.vision}
**Time Horizon**: ${roadmap.timeHorizon}
**Owner**: ${roadmap.owner}
**Status**: ${roadmap.status}

**Roadmap ID**: ${roadmap.id}

Next steps:
1. Add strategic themes using add_roadmap_theme
2. Create initiatives within themes
3. Add features to initiatives
4. Set up milestones and releases
5. Prioritize features using prioritize_features`
          }]
        };
      }

      case 'add_roadmap_theme': {
        const params = args as unknown as AddThemeOptions;
        const theme = await roadmapManager.addTheme(params);
        
        return {
          content: [{
            type: 'text',
            text: `✅ Theme "${theme.name}" added to roadmap!

**Description**: ${theme.description}
**Priority**: ${theme.priority}
**Timeframe**: ${theme.timeframe.startQuarter} - ${theme.timeframe.endQuarter}

**Objectives**:
${theme.objectives.map((obj, i) => `${i + 1}. ${obj}`).join('\n')}

**Theme ID**: ${theme.id}

Next: Create initiatives within this theme using create_initiative`
          }]
        };
      }

      case 'create_initiative': {
        const params = args as unknown as CreateInitiativeOptions;
        const initiative = await roadmapManager.createInitiative(params);
        
        const totalEffort = params.estimatedEffort.developmentWeeks + 
                           params.estimatedEffort.designWeeks + 
                           params.estimatedEffort.qaWeeks;
        
        return {
          content: [{
            type: 'text',
            text: `✅ Initiative "${initiative.title}" created!

**Description**: ${initiative.description}

**Estimated Value**:
- User Impact: ${initiative.value.userImpact}
- Revenue Impact: $${initiative.value.revenueImpact.toLocaleString()}
- Cost Savings: $${initiative.value.costSavings.toLocaleString()}
- Strategic Value: ${initiative.value.strategicValue}/10
- Customer Satisfaction: ${initiative.value.customerSatisfaction > 0 ? '+' : ''}${initiative.value.customerSatisfaction} NPS

**Estimated Effort**: ${totalEffort} weeks total
- Development: ${initiative.effort.developmentWeeks} weeks
- Design: ${initiative.effort.designWeeks} weeks
- QA: ${initiative.effort.qaWeeks} weeks
- Confidence: ${initiative.effort.confidence}

**Risks**: ${initiative.risks.length} identified

**Initiative ID**: ${initiative.id}

Next: Add features to this initiative using add_feature`
          }]
        };
      }

      case 'add_feature': {
        const params = args as unknown as AddFeatureOptions;
        const feature = await roadmapManager.addFeature(params);
        
        return {
          content: [{
            type: 'text',
            text: `✅ Feature "${feature.name}" added!

**Description**: ${feature.description}
**Business Value**: ${feature.businessValue.score}/100
**Technical Complexity**: ${feature.technicalComplexity}
**Status**: ${feature.status}
${feature.targetRelease ? `**Target Release**: ${feature.targetRelease}` : ''}

**Value Rationale**: ${feature.businessValue.rationale}

**Success Metrics**:
${feature.businessValue.metrics.map((metric, i) => `${i + 1}. ${metric}`).join('\n')}

**Feature ID**: ${feature.id}`
          }]
        };
      }

      case 'prioritize_features': {
        const params = args as any;
        const roadmap = await roadmapManager.getRoadmap(params.roadmapId);
  
  if (!roadmap) {
    throw new Error(`Roadmap ${params.roadmapId} not found`);
  }
  
  // Collect features based on scope
  const features: Feature[] = [];
  const themes = await Promise.all(
    roadmap.themes.map(t => roadmapManager.getThemeDetails(t.id))
  );
  
  for (const themeData of themes) {
    if (themeData) {
      if (params.scope === 'all' || 
          (params.scope === 'theme' && params.scopeId === themeData.theme.id)) {
        features.push(...themeData.features);
      } else if (params.scope === 'initiative') {
        const initiativeFeatures = themeData.features.filter(
          f => f.initiativeId === params.scopeId
        );
        features.push(...initiativeFeatures);
      } else if (params.scope === 'unscheduled') {
        const unscheduledFeatures = themeData.features.filter(
          f => !f.targetRelease
        );
        features.push(...unscheduledFeatures);
      }
    }
  }
  
  const criteria: PrioritizationCriteria = {
    method: params.method,
    weights: params.weights
  };
  
  const results = await prioritizationEngine.prioritizeFeatures(features, criteria);
  
  // Format results
  const topFeatures = results.slice(0, 10);
  const featureDetails = topFeatures.map(result => {
    const feature = features.find(f => f.id === result.featureId);
    return {
      rank: result.rank,
      name: feature?.name || 'Unknown',
      score: result.score,
      rationale: result.rationale
    };
  });
  
        return {
          content: [{
            type: 'text',
            text: `📊 Feature Prioritization Results (${params.method.toUpperCase()})

**Scope**: ${params.scope}${params.scopeId ? ` (${params.scopeId})` : ''}
**Features Analyzed**: ${features.length}

**Top 10 Features**:
${featureDetails.map(f => 
  `${f.rank}. **${f.name}**\n   Score: ${f.score.toFixed(2)}\n   ${f.rationale}`
).join('\n\n')}

${results.length > 10 ? `\n... and ${results.length - 10} more features` : ''}`
          }]
        };
      }

      case 'generate_roadmap_timeline': {
        const params = args as any;
        const roadmap = await roadmapManager.getRoadmap(params.roadmapId);
  
  if (!roadmap) {
    throw new Error(`Roadmap ${params.roadmapId} not found`);
  }
  
  let timelineView: TimelineView;
  
  switch (params.viewType) {
    case 'quarterly':
      timelineView = timelineGenerator.generateQuarterlyView(
        roadmap,
        params.startPeriod,
        params.endPeriod
      );
      break;
      
    case 'monthly':
      const startMonth = new Date(params.startPeriod);
      const initiatives: Initiative[] = [];
      const features: Feature[] = [];
      
      // Collect all initiatives and features
      for (const theme of roadmap.themes) {
        const themeDetails = await roadmapManager.getThemeDetails(theme.id);
        if (themeDetails) {
          initiatives.push(...themeDetails.initiatives);
          features.push(...themeDetails.features);
        }
      }
      
      timelineView = timelineGenerator.generateMonthlyView(
        roadmap,
        initiatives,
        features,
        startMonth,
        params.months || 6
      );
      break;
      
    case 'release':
      const featureMap = new Map<string, Feature>();
      // Collect all features
      for (const theme of roadmap.themes) {
        const themeDetails = await roadmapManager.getThemeDetails(theme.id);
        if (themeDetails) {
          themeDetails.features.forEach(f => featureMap.set(f.id, f));
        }
      }
      
      timelineView = timelineGenerator.generateReleaseView(roadmap, featureMap);
      break;
      
    case 'now-next-later':
      const themeMap = new Map<string, RoadmapTheme>();
      const initiativeMap = new Map<string, Initiative>();
      const allFeatures = new Map<string, Feature>();
      
      // Collect all data
      for (const theme of roadmap.themes) {
        themeMap.set(theme.id, theme);
        const themeDetails = await roadmapManager.getThemeDetails(theme.id);
        if (themeDetails) {
          themeDetails.initiatives.forEach(i => initiativeMap.set(i.id, i));
          themeDetails.features.forEach(f => allFeatures.set(f.id, f));
        }
      }
      
      timelineView = timelineGenerator.generateNowNextLaterView(
        roadmap,
        themeMap,
        initiativeMap,
        allFeatures
      );
      break;
      
    default:
      throw new Error(`Unknown view type: ${params.viewType}`);
  }
  
  // Generate Gantt data
  const ganttData = timelineGenerator.generateGanttData(timelineView);
  const criticalPath = timelineGenerator.findCriticalPath(timelineView.items);
  
  // Format timeline items
  const itemsByType = timelineView.items.reduce((acc, item) => {
    if (!acc[item.type]) acc[item.type] = [];
    acc[item.type].push(item);
    return acc;
  }, {} as Record<string, typeof timelineView.items>);
  
        return {
          content: [{
            type: 'text',
            text: `📅 ${params.viewType.charAt(0).toUpperCase() + params.viewType.slice(1)} Timeline View

**Period**: ${timelineView.startDate.toLocaleDateString()} - ${timelineView.endDate.toLocaleDateString()}
**Total Items**: ${timelineView.items.length}

${Object.entries(itemsByType).map(([type, items]) => `
**${type.charAt(0).toUpperCase() + type.slice(1)}s** (${items.length}):
${items.slice(0, 5).map(item => 
  `- ${item.name} (${item.startDate.toLocaleDateString()}${
    item.startDate !== item.endDate ? ` - ${item.endDate.toLocaleDateString()}` : ''
  })${item.progress !== undefined ? ` [${item.progress}%]` : ''}`
).join('\n')}${items.length > 5 ? `\n  ... and ${items.length - 5} more` : ''}`
).join('\n')}

**Critical Path**: ${criticalPath.length > 0 ? 
  criticalPath.map(id => {
    const item = timelineView.items.find(i => i.id === id);
    return item?.name || id;
  }).join(' → ') : 'No dependencies defined'}`
          }]
        };
      }

      case 'create_milestone': {
        const params = args as any;
        const milestone = await roadmapManager.createMilestone(params.roadmapId, {
    name: params.name,
    date: new Date(params.date),
    type: params.type,
    description: params.description,
    deliverables: params.deliverables,
    status: 'upcoming',
    dependencies: params.dependencies || []
  });
  
        return {
          content: [{
            type: 'text',
            text: `✅ Milestone "${milestone.name}" created!

**Date**: ${milestone.date.toLocaleDateString()}
**Type**: ${milestone.type}
**Description**: ${milestone.description}

**Deliverables**:
${milestone.deliverables.map((d, i) => `${i + 1}. ${d}`).join('\n')}

${milestone.dependencies.length > 0 ? `**Dependencies**: ${milestone.dependencies.join(', ')}` : ''}

**Milestone ID**: ${milestone.id}`
          }]
        };
      }

      case 'plan_release': {
        const params = args as any;
        const release = await roadmapManager.planRelease(params.roadmapId, {
    version: params.version,
    name: params.name,
    date: new Date(params.date),
    features: params.features,
    themes: params.themes || [],
    goals: params.goals,
    notes: params.notes
  });
  
        return {
          content: [{
            type: 'text',
            text: `✅ Release v${release.version} planned!

**Name**: ${release.name}
**Date**: ${release.date.toLocaleDateString()}
**Status**: ${release.status}

**Goals**:
${release.goals.map((g, i) => `${i + 1}. ${g}`).join('\n')}

**Features**: ${release.features.length} features included
**Themes**: ${release.themes.length} themes addressed

${release.notes ? `**Notes**: ${release.notes}` : ''}

**Release ID**: ${release.id}`
          }]
        };
      }

      case 'update_feature_status': {
        const params = args as any;
        const feature = await roadmapManager.updateFeatureStatus(params.featureId, params.status);
        
        return {
          content: [{
            type: 'text',
            text: `✅ Feature "${feature.name}" status updated to: ${feature.status}`
          }]
        };
      }

      case 'update_initiative_status': {
        const params = args as any;
        const initiative = await roadmapManager.updateInitiativeStatus(params.initiativeId, params.status);
        
        return {
          content: [{
            type: 'text',
            text: `✅ Initiative "${initiative.title}" status updated to: ${initiative.status}`
          }]
        };
      }

      case 'get_roadmap_health': {
        const params = args as any;
        const health = await roadmapManager.getRoadmapHealth(params.roadmapId);
  
  const healthEmoji = {
    'excellent': '🟢',
    'good': '🟡',
    'at-risk': '🟠',
    'critical': '🔴'
  };
  
        return {
          content: [{
            type: 'text',
            text: `${healthEmoji[health.health]} Roadmap Health: **${health.health.toUpperCase()}**

**Metrics**:
- Features Planned: ${health.metrics.featuresPlanned}
- Features Completed: ${health.metrics.featuresCompleted} (${
  health.metrics.featuresPlanned > 0 ? 
  Math.round((health.metrics.featuresCompleted / health.metrics.featuresPlanned) * 100) : 0
}%)
- Active Initiatives: ${health.metrics.initiativesActive}
- Velocity Trend: ${health.metrics.velocityTrend}
- On-Time Delivery: ${health.metrics.onTimeDelivery}%
- Value Delivered: ${health.metrics.valueDelivered}%

${health.risks.length > 0 ? `**Risks**:\n${health.risks.map(r => `- ⚠️ ${r}`).join('\n')}` : ''}

${health.recommendations.length > 0 ? `\n**Recommendations**:\n${health.recommendations.map(r => `- 💡 ${r}`).join('\n')}` : ''}`
          }]
        };
      }

      case 'list_roadmaps': {
        const roadmaps = await roadmapManager.getRoadmaps();
  
        if (roadmaps.length === 0) {
          return {
            content: [{
              type: 'text',
              text: 'No product roadmaps found. Create one using create_roadmap.'
            }]
          };
        }
        
        return {
          content: [{
            type: 'text',
            text: `📋 Product Roadmaps (${roadmaps.length}):

${roadmaps.map(r => `
**${r.name}** (${r.id})
- Vision: ${r.vision}
- Time Horizon: ${r.timeHorizon}
- Status: ${r.status}
- Owner: ${r.owner}
- Themes: ${r.themes.length}
- Updated: ${r.updatedAt.toLocaleDateString()}`
).join('\n')}`
          }]
        };
      }

      case 'get_roadmap': {
        const params = args as any;
        const roadmap = await roadmapManager.getRoadmap(params.roadmapId);
  
  if (!roadmap) {
    throw new Error(`Roadmap ${params.roadmapId} not found`);
  }
  
  const themeDetails = await Promise.all(
    roadmap.themes.map(t => roadmapManager.getThemeDetails(t.id))
  );
  
  let totalInitiatives = 0;
  let totalFeatures = 0;
  
  for (const td of themeDetails) {
    if (td) {
      totalInitiatives += td.initiatives.length;
      totalFeatures += td.features.length;
    }
  }
  
        return {
          content: [{
            type: 'text',
            text: `# ${roadmap.name}

**Vision**: ${roadmap.vision}
**Time Horizon**: ${roadmap.timeHorizon}
**Status**: ${roadmap.status}
**Owner**: ${roadmap.owner}

## Overview
- Themes: ${roadmap.themes.length}
- Initiatives: ${totalInitiatives}
- Features: ${totalFeatures}
- Milestones: ${roadmap.milestones.length}
- Releases: ${roadmap.releases.length}

## Themes
${roadmap.themes.map(theme => {
  const td = themeDetails.find(d => d?.theme.id === theme.id);
  return `
### ${theme.name}
- Priority: ${theme.priority}
- Timeframe: ${theme.timeframe.startQuarter} - ${theme.timeframe.endQuarter}
- Status: ${theme.status}
- Progress: ${theme.metrics.progressPercentage}%
- Initiatives: ${td?.initiatives.length || 0}
- Features: ${td?.features.length || 0}`;
}).join('\n')}

## Upcoming Milestones
${roadmap.milestones
  .filter(m => m.status === 'upcoming')
  .sort((a, b) => a.date.getTime() - b.date.getTime())
  .slice(0, 5)
  .map(m => `- ${m.name} (${m.date.toLocaleDateString()})`)
  .join('\n') || 'No upcoming milestones'}

## Metrics
- On-Time Delivery: ${roadmap.metrics.onTimeDelivery}%
- Value Delivered: ${roadmap.metrics.valueDelivered}%
- Velocity Trend: ${roadmap.metrics.velocityTrend}`
          }]
        };
      }

      case 'get_theme_details': {
        const params = args as any;
        const themeDetails = await roadmapManager.getThemeDetails(params.themeId);
  
  if (!themeDetails) {
    throw new Error(`Theme ${params.themeId} not found`);
  }
  
  const { theme, initiatives, features } = themeDetails;
  
        return {
          content: [{
            type: 'text',
            text: `# Theme: ${theme.name}

**Description**: ${theme.description}
**Priority**: ${theme.priority}
**Timeframe**: ${theme.timeframe.startQuarter} - ${theme.timeframe.endQuarter}
**Status**: ${theme.status}
**Progress**: ${theme.metrics.progressPercentage}%

## Objectives
${theme.objectives.map((obj, i) => `${i + 1}. ${obj}`).join('\n')}

## Metrics
- Total Initiatives: ${theme.metrics.initiativesTotal}
- Completed Initiatives: ${theme.metrics.initiativesCompleted}
- Total Features: ${theme.metrics.featuresTotal}
- Completed Features: ${theme.metrics.featuresCompleted}

## Initiatives (${initiatives.length})
${initiatives.map(i => `
### ${i.title}
- Status: ${i.status}
- Features: ${i.features.length}
- User Impact: ${i.value.userImpact}
- Revenue Impact: $${i.value.revenueImpact.toLocaleString()}
- Strategic Value: ${i.value.strategicValue}/10`
).join('\n')}

## Features (${features.length})
${features.slice(0, 10).map(f => 
  `- **${f.name}** - ${f.status} (Value: ${f.businessValue.score}/100, Complexity: ${f.technicalComplexity})`
).join('\n')}${features.length > 10 ? `\n... and ${features.length - 10} more features` : ''}`
          }]
        };
      }

      case 'start_roadmap_wizard': {
        const params = args as any;
        const result = await roadmapWizard.startRoadmapWizard(params.sessionId);
        
        return {
          content: [{
            type: 'text',
            text: result
          }]
        };
      }

      case 'continue_roadmap_wizard': {
        const params = args as any;
        const result = await roadmapWizard.continueRoadmapWizard(params.sessionId, params.input);
        
        return {
          content: [{
            type: 'text',
            text: result
          }]
        };
      }

      case 'create_initiative_wizard': {
        const params = args as any;
        const result = await roadmapWizard.startInitiativeWizard(
          params.sessionId, 
          params.roadmapId,
          params.themeId
        );
        
        return {
          content: [{
            type: 'text',
            text: result
          }]
        };
      }

      case 'continue_initiative_wizard': {
        const params = args as any;
        const result = await roadmapWizard.continueInitiativeWizard(params.sessionId, params.input);
        
        return {
          content: [{
            type: 'text',
            text: result
          }]
        };
      }

      default:
        throw new Error(`Unknown tool: ${name}`);
    }
  });

  return {
    tools: [
      {
        name: 'create_roadmap',
        description: 'Create a new product roadmap with vision and strategic timeline',
        inputSchema: {
          type: 'object',
          properties: {
            name: { type: 'string', description: 'Name of the product roadmap' },
            vision: { type: 'string', description: 'Product vision statement' },
            timeHorizon: { 
              type: 'string', 
              enum: ['quarterly', 'annual', 'multi-year'],
              description: 'Planning time horizon' 
            },
            owner: { type: 'string', description: 'Product owner name' },
            stakeholders: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of stakeholder names'
            }
          },
          required: ['name', 'vision', 'timeHorizon', 'owner']
        }
      },
      {
        name: 'add_roadmap_theme',
        description: 'Add a strategic theme to a product roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            name: { type: 'string', description: 'Theme name' },
            description: { type: 'string', description: 'Theme description' },
            objectives: {
              type: 'array',
              items: { type: 'string' },
              description: 'Strategic objectives'
            },
            priority: {
              type: 'string',
              enum: ['must-have', 'should-have', 'nice-to-have'],
              description: 'Theme priority'
            },
            startQuarter: { type: 'string', description: 'Start quarter (e.g., Q1 2024)' },
            endQuarter: { type: 'string', description: 'End quarter' }
          },
          required: ['roadmapId', 'name', 'description', 'objectives', 'priority', 'startQuarter', 'endQuarter']
        }
      },
      {
        name: 'create_initiative',
        description: 'Create a product initiative within a theme',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            themeId: { type: 'string', description: 'ID of the theme' },
            title: { type: 'string', description: 'Initiative title' },
            description: { type: 'string', description: 'Initiative description' },
            estimatedValue: {
              type: 'object',
              properties: {
                userImpact: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
                revenueImpact: { type: 'number', description: 'Estimated revenue impact' },
                costSavings: { type: 'number', description: 'Estimated cost savings' },
                strategicValue: { type: 'number', description: 'Strategic value (1-10)' },
                customerSatisfaction: { type: 'number', description: 'Projected NPS impact' }
              },
              required: ['userImpact', 'revenueImpact', 'costSavings', 'strategicValue', 'customerSatisfaction']
            },
            estimatedEffort: {
              type: 'object',
              properties: {
                developmentWeeks: { type: 'number' },
                designWeeks: { type: 'number' },
                qaWeeks: { type: 'number' },
                confidence: { type: 'string', enum: ['low', 'medium', 'high'] }
              },
              required: ['developmentWeeks', 'designWeeks', 'qaWeeks', 'confidence']
            },
            risks: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  description: { type: 'string' },
                  likelihood: { type: 'string', enum: ['low', 'medium', 'high'] },
                  impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                  mitigation: { type: 'string' }
                },
                required: ['description', 'likelihood', 'impact', 'mitigation']
              }
            }
          },
          required: ['roadmapId', 'themeId', 'title', 'description', 'estimatedValue', 'estimatedEffort']
        }
      },
      {
        name: 'add_feature',
        description: 'Add a feature to an initiative',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            initiativeId: { type: 'string', description: 'ID of the initiative' },
            name: { type: 'string', description: 'Feature name' },
            description: { type: 'string', description: 'Feature description' },
            businessValue: {
              type: 'object',
              properties: {
                score: { type: 'number', description: 'Business value score (1-100)' },
                rationale: { type: 'string', description: 'Value rationale' },
                metrics: {
                  type: 'array',
                  items: { type: 'string' },
                  description: 'Success metrics'
                }
              },
              required: ['score', 'rationale', 'metrics']
            },
            technicalComplexity: {
              type: 'string',
              enum: ['low', 'medium', 'high', 'very-high'],
              description: 'Technical complexity'
            },
            targetRelease: { type: 'string', description: 'Target release ID (optional)' }
          },
          required: ['roadmapId', 'initiativeId', 'name', 'description', 'businessValue', 'technicalComplexity']
        }
      },
      {
        name: 'prioritize_features',
        description: 'Prioritize features using various methods (RICE, MoSCoW, Value-Effort, etc.)',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            method: {
              type: 'string',
              enum: ['rice', 'value-effort', 'moscow', 'kano', 'custom'],
              description: 'Prioritization method'
            },
            weights: {
              type: 'object',
              properties: {
                businessValue: { type: 'number' },
                userImpact: { type: 'number' },
                strategicAlignment: { type: 'number' },
                technicalFeasibility: { type: 'number' },
                risk: { type: 'number' }
              },
              description: 'Custom weights (only for custom method)'
            },
            scope: {
              type: 'string',
              enum: ['all', 'theme', 'initiative', 'unscheduled'],
              description: 'Scope of prioritization'
            },
            scopeId: { type: 'string', description: 'ID of theme/initiative if scope is specific' }
          },
          required: ['roadmapId', 'method']
        }
      },
      {
        name: 'generate_roadmap_timeline',
        description: 'Generate timeline views of the roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            viewType: {
              type: 'string',
              enum: ['quarterly', 'monthly', 'release', 'now-next-later'],
              description: 'Type of timeline view'
            },
            startPeriod: { type: 'string', description: 'Start quarter/month (for quarterly/monthly views)' },
            endPeriod: { type: 'string', description: 'End quarter/month (for quarterly view)' },
            months: { type: 'number', description: 'Number of months (for monthly view)' }
          },
          required: ['roadmapId', 'viewType']
        }
      },
      {
        name: 'create_milestone',
        description: 'Create a milestone in the roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            name: { type: 'string', description: 'Milestone name' },
            date: { type: 'string', description: 'Milestone date (ISO format)' },
            type: {
              type: 'string',
              enum: ['release', 'business', 'technical', 'regulatory'],
              description: 'Type of milestone'
            },
            description: { type: 'string', description: 'Milestone description' },
            deliverables: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of deliverables'
            },
            dependencies: {
              type: 'array',
              items: { type: 'string' },
              description: 'List of dependency IDs'
            }
          },
          required: ['roadmapId', 'name', 'date', 'type', 'description', 'deliverables']
        }
      },
      {
        name: 'plan_release',
        description: 'Plan a product release',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            version: { type: 'string', description: 'Release version' },
            name: { type: 'string', description: 'Release name' },
            date: { type: 'string', description: 'Release date (ISO format)' },
            features: {
              type: 'array',
              items: { type: 'string' },
              description: 'Feature IDs to include'
            },
            themes: {
              type: 'array',
              items: { type: 'string' },
              description: 'Theme IDs addressed'
            },
            goals: {
              type: 'array',
              items: { type: 'string' },
              description: 'Release goals'
            },
            notes: { type: 'string', description: 'Release notes' }
          },
          required: ['roadmapId', 'version', 'name', 'date', 'features', 'goals']
        }
      },
      {
        name: 'update_feature_status',
        description: 'Update the status of a feature',
        inputSchema: {
          type: 'object',
          properties: {
            featureId: { type: 'string', description: 'ID of the feature' },
            status: {
              type: 'string',
              enum: ['proposed', 'approved', 'in-progress', 'completed', 'cancelled'],
              description: 'New status'
            }
          },
          required: ['featureId', 'status']
        }
      },
      {
        name: 'update_initiative_status',
        description: 'Update the status of an initiative',
        inputSchema: {
          type: 'object',
          properties: {
            initiativeId: { type: 'string', description: 'ID of the initiative' },
            status: {
              type: 'string',
              enum: ['ideation', 'validated', 'scheduled', 'in-development', 'launched'],
              description: 'New status'
            }
          },
          required: ['initiativeId', 'status']
        }
      },
      {
        name: 'get_roadmap_health',
        description: 'Get health assessment and metrics for a roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' }
          },
          required: ['roadmapId']
        }
      },
      {
        name: 'list_roadmaps',
        description: 'List all product roadmaps',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        }
      },
      {
        name: 'get_roadmap',
        description: 'Get detailed information about a specific roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            roadmapId: { type: 'string', description: 'ID of the roadmap' }
          },
          required: ['roadmapId']
        }
      },
      {
        name: 'get_theme_details',
        description: 'Get detailed information about a theme including initiatives and features',
        inputSchema: {
          type: 'object',
          properties: {
            themeId: { type: 'string', description: 'ID of the theme' }
          },
          required: ['themeId']
        }
      },
      {
        name: 'start_roadmap_wizard',
        description: 'Start an interactive wizard to create a comprehensive product roadmap',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Unique session ID for the wizard' }
          },
          required: ['sessionId']
        }
      },
      {
        name: 'continue_roadmap_wizard',
        description: 'Continue the roadmap creation wizard with user input',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Session ID for the wizard' },
            input: { type: 'object', description: 'User input for the current step' }
          },
          required: ['sessionId', 'input']
        }
      },
      {
        name: 'create_initiative_wizard',
        description: 'Start an interactive wizard to create an initiative within a theme',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Unique session ID for the wizard' },
            roadmapId: { type: 'string', description: 'ID of the roadmap' },
            themeId: { type: 'string', description: 'ID of the theme' }
          },
          required: ['sessionId', 'roadmapId', 'themeId']
        }
      },
      {
        name: 'continue_initiative_wizard',
        description: 'Continue the initiative creation wizard with user input',
        inputSchema: {
          type: 'object',
          properties: {
            sessionId: { type: 'string', description: 'Session ID for the wizard' },
            input: { type: 'object', description: 'User input for the current step' }
          },
          required: ['sessionId', 'input']
        }
      }
    ]
  };
}