import { Application, Request, Response } from 'express';

export function setupAgileAPI(app: Application, agileManager: any): void {
  // Agile management API endpoints setup

  // Get all sprints
  app.get('/api/agile/sprints', async (req: Request, res: Response) => {
    try {
      const { status, limit = 10 } = req.query;
      
      let sprints = [];
      
      if (agileManager.getSprints) {
        // Use the available getSprints method
        const filter: any = {};
        if (status) filter.status = status;
        sprints = await agileManager.getSprints(filter);
        
        // Apply limit if specified
        if (limit && Number(limit) > 0) {
          sprints = sprints.slice(0, Number(limit));
        }
      } else {
        // Return mock data if agile manager doesn't have sprint methods
        sprints = [
          {
            id: 'SPRINT-001',
            name: 'Sprint 1 - Foundation',
            status: 'active',
            startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
            endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
            goal: 'Establish core project infrastructure and authentication',
            storyPointsPlanned: 34,
            storyPointsCompleted: 21,
            storiesTotal: 8,
            storiesCompleted: 5
          }
        ];
      }
      
      res.json({
        success: true,
        data: { sprints },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching sprints:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch sprints',
        message: (error as Error).message
      });
    }
  });

  // Get active sprint
  app.get('/api/agile/sprints/active', async (req: Request, res: Response) => {
    try {
      let activeSprint = null;
      
      if (agileManager.getActiveSprint) {
        activeSprint = await agileManager.getActiveSprint();
      } else {
        // Return mock active sprint
        activeSprint = {
          id: 'SPRINT-001',
          name: 'Sprint 1 - Foundation',
          status: 'active',
          startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
          goal: 'Establish core project infrastructure and authentication'
        };
      }
      
      if (!activeSprint) {
        return res.status(404).json({
          success: false,
          error: 'No active sprint found'
        });
      }
      
      res.json({
        success: true,
        data: activeSprint,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching active sprint:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch active sprint',
        message: (error as Error).message
      });
    }
  });

  // Get specific sprint details
  app.get('/api/agile/sprints/:id', async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      
      let sprint = null;
      
      if (agileManager.getSprintById) {
        sprint = await agileManager.getSprintById(id);
      } else if (agileManager.getSprint) {
        sprint = await agileManager.getSprint(id);
      } else {
        // Return mock data
        sprint = {
          id,
          name: 'Sprint 1 - Foundation',
          status: 'active',
          startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
          goal: 'Establish core project infrastructure and authentication',
          storyPointsPlanned: 34,
          storyPointsCompleted: 21,
          storiesTotal: 8,
          storiesCompleted: 5,
          stories: [
            {
              id: 'STORY-001',
              title: 'User Authentication System',
              description: 'Implement secure user login and registration',
              status: 'done',
              storyPoints: 8,
              assignee: 'John Doe',
              priority: 'high'
            },
            {
              id: 'STORY-002', 
              title: 'Database Schema Setup',
              description: 'Create initial database tables and relationships',
              status: 'in-progress',
              storyPoints: 5,
              assignee: 'Jane Smith',
              priority: 'high'
            }
          ]
        };
      }
      
      if (!sprint) {
        return res.status(404).json({
          success: false,
          error: 'Sprint not found',
          sprintId: id
        });
      }
      
      res.json({
        success: true,
        data: sprint,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error(`📋 Error fetching sprint ${req.params.id}:`, error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch sprint details',
        message: (error as Error).message
      });
    }
  });

  // Get stories with filtering
  app.get('/api/agile/stories', async (req: Request, res: Response) => {
    try {
      const { 
        sprintId, 
        status, 
        assignee, 
        priority,
        limit = 50,
        offset = 0 
      } = req.query;
      
      const filters = {
        sprintId,
        status,
        assignee,
        priority,
        limit: Number(limit),
        offset: Number(offset)
      };
      
      let stories = [];
      
      if (agileManager.getBacklog) {
        // Use the available getBacklog method to get all stories
        const allStories = await agileManager.getBacklog();
        stories = allStories;
        
        // Apply filters
        if (sprintId) {
          stories = stories.filter((story: any) => story.sprintId === sprintId);
        }
        if (status) {
          stories = stories.filter((story: any) => story.status === status);
        }
        if (assignee) {
          stories = stories.filter((story: any) => story.assignee === assignee);
        }
        if (priority) {
          stories = stories.filter((story: any) => story.priority === priority);
        }
        
        // Apply pagination
        const startIndex = Number(offset);
        const endIndex = startIndex + Number(limit);
        stories = stories.slice(startIndex, endIndex);
      } else {
        // Return mock data
        stories = [
          {
            id: 'STORY-001',
            title: 'User Authentication System',
            description: 'Implement secure user login and registration with JWT tokens',
            status: 'done',
            storyPoints: 8,
            assignee: 'John Doe',
            priority: 'high',
            sprintId: 'SPRINT-001',
            tags: ['authentication', 'security'],
            createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'STORY-002',
            title: 'Database Schema Setup',
            description: 'Create initial database tables and relationships for user management',
            status: 'in-progress',
            storyPoints: 5,
            assignee: 'Jane Smith',
            priority: 'high',
            sprintId: 'SPRINT-001',
            tags: ['database', 'setup'],
            createdAt: new Date(Date.now() - 9 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'STORY-003',
            title: 'API Rate Limiting',
            description: 'Implement rate limiting middleware for API endpoints',
            status: 'todo',
            storyPoints: 3,
            assignee: 'Bob Johnson',
            priority: 'medium',
            sprintId: 'SPRINT-001',
            tags: ['api', 'security', 'middleware'],
            createdAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
          }
        ];
        
        // Apply filters to mock data
        if (status) {
          stories = stories.filter(story => story.status === status);
        }
        if (assignee) {
          stories = stories.filter(story => story.assignee.toLowerCase().includes((assignee as string).toLowerCase()));
        }
        if (priority) {
          stories = stories.filter(story => story.priority === priority);
        }
        if (sprintId) {
          stories = stories.filter(story => story.sprintId === sprintId);
        }
      }
      
      res.json({
        success: true,
        data: { stories },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching stories:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch stories',
        message: (error as Error).message
      });
    }
  });

  // Move story between columns
  app.post('/api/agile/story/move', async (req: Request, res: Response) => {
    try {
      const { storyId, fromStatus, toStatus, index } = req.body;
      
      if (!storyId || !toStatus) {
        return res.status(400).json({
          success: false,
          error: 'Missing required fields: storyId and toStatus are required'
        });
      }

      let result = null;
      
      if (agileManager.moveStory) {
        result = await agileManager.moveStory(storyId, toStatus, index);
      } else if (agileManager.updateStory) {
        result = await agileManager.updateStory(storyId, { status: toStatus });
      } else {
        // Mock successful move
        result = {
          storyId,
          fromStatus,
          toStatus,
          index,
          updatedAt: new Date().toISOString()
        };
      }
      
      res.json({
        success: true,
        message: 'Story moved successfully',
        data: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error moving story:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to move story',
        message: (error as Error).message
      });
    }
  });

  // Update story details
  app.put('/api/agile/stories/:id', async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      const updates = req.body;
      
      let result = null;
      
      if (agileManager.updateStory) {
        result = await agileManager.updateStory(id, updates);
      } else {
        // Mock successful update
        result = {
          storyId: id,
          updates,
          updatedAt: new Date().toISOString()
        };
      }
      
      res.json({
        success: true,
        message: 'Story updated successfully',
        data: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error(`📋 Error updating story ${req.params.id}:`, error);
      res.status(500).json({
        success: false,
        error: 'Failed to update story',
        message: (error as Error).message
      });
    }
  });

  // Get velocity data for charts
  app.get('/api/agile/velocity', async (req: Request, res: Response) => {
    try {
      const { teamName, sprints = '5' } = req.query;
      
      let velocityData = null;
      
      if (agileManager.calculateVelocity) {
        velocityData = await agileManager.calculateVelocity({ teamName, lastNSprints: Number(sprints) });
      } else if (agileManager.getVelocityData) {
        velocityData = await agileManager.getVelocityData({ teamName, sprints: Number(sprints) });
      } else {
        // Return mock velocity data
        velocityData = {
          teamName: teamName || 'default',
          sprints: [
            { name: 'Sprint 1', planned: 30, completed: 28, completionRate: 93.3 },
            { name: 'Sprint 2', planned: 32, completed: 25, completionRate: 78.1 },
            { name: 'Sprint 3', planned: 28, completed: 31, completionRate: 110.7 },
            { name: 'Sprint 4', planned: 35, completed: 33, completionRate: 94.3 },
            { name: 'Sprint 5', planned: 30, completed: 29, completionRate: 96.7 },
            { name: 'Sprint 6', planned: 34, completed: 21, completionRate: 61.8 }
          ],
          averageVelocity: 27.8,
          trend: 'stable'
        };
      }
      
      res.json({
        success: true,
        data: velocityData,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching velocity data:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch velocity data',
        message: (error as Error).message
      });
    }
  });

  // Get burndown chart data for a sprint
  app.get('/api/agile/burndown/:sprintId', async (req: Request, res: Response) => {
    try {
      const { sprintId } = req.params;
      
      let burndownData = null;
      
      if (agileManager.getBurndownData) {
        burndownData = await agileManager.getBurndownData(sprintId);
      } else {
        // Return mock burndown data
        const sprintDays = 14;
        const totalPoints = 34;
        const currentDay = 8;
        
        const idealBurndown = [];
        const actualBurndown = [];
        
        for (let day = 0; day <= sprintDays; day++) {
          idealBurndown.push({
            day,
            remaining: Math.max(0, totalPoints - (totalPoints / sprintDays) * day)
          });
        }
        
        // Mock actual progress with some variance
        const actualProgress = [34, 34, 31, 28, 28, 25, 22, 19, 13]; // Current day 8
        for (let day = 0; day < actualProgress.length; day++) {
          actualBurndown.push({
            day,
            remaining: actualProgress[day]
          });
        }
        
        burndownData = {
          sprintId,
          totalStoryPoints: totalPoints,
          currentDay,
          sprintDays,
          idealBurndown,
          actualBurndown,
          projectedCompletion: currentDay + Math.ceil(actualProgress[actualProgress.length - 1] / 2.5),
          onTrack: true
        };
      }
      
      res.json({
        success: true,
        data: burndownData,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error(`📋 Error fetching burndown data for sprint ${req.params.sprintId}:`, error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch burndown data',
        message: (error as Error).message
      });
    }
  });

  // Get board configuration (columns, workflow states)
  app.get('/api/agile/board/config', async (req: Request, res: Response) => {
    try {
      let boardConfig = null;
      
      if (agileManager.getBoardConfig) {
        boardConfig = await agileManager.getBoardConfig();
      } else {
        // Return default board configuration
        boardConfig = {
          columns: [
            { id: 'todo', name: 'To Do', wip: null, color: '#f0f0f0' },
            { id: 'in-progress', name: 'In Progress', wip: 3, color: '#ffeaa7' },
            { id: 'review', name: 'Review', wip: 2, color: '#74b9ff' },
            { id: 'done', name: 'Done', wip: null, color: '#00b894' }
          ],
          storyStates: ['todo', 'in-progress', 'review', 'done'],
          defaultAssignees: ['John Doe', 'Jane Smith', 'Bob Johnson'],
          priorities: ['low', 'medium', 'high', 'critical'],
          storyPointScale: [1, 2, 3, 5, 8, 13, 21]
        };
      }
      
      res.json({
        success: true,
        data: boardConfig,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching board configuration:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch board configuration',
        message: (error as Error).message
      });
    }
  });

  // Health check for agile service
  app.get('/api/agile/health', async (req: Request, res: Response) => {
    try {
      const features = {
        sprints: !!agileManager.getSprints || !!agileManager.getCurrentSprints,
        stories: !!agileManager.getStories || !!agileManager.getActiveStories,
        velocity: !!agileManager.getVelocityData,
        burndown: !!agileManager.getBurndownData,
        storyUpdates: !!agileManager.updateStory,
        storyMovement: !!agileManager.moveStory
      };
      
      res.json({
        success: true,
        status: 'healthy',
        data: {
          agileManagerAvailable: !!agileManager,
          features
        },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Agile service health check failed:', error);
      res.status(503).json({
        success: false,
        status: 'unhealthy',
        error: 'Agile service is not functioning properly',
        message: (error as Error).message,
        timestamp: new Date().toISOString()
      });
    }
  });

  // Get all boards
  app.get('/api/agile/boards', async (req: Request, res: Response) => {
    try {
      let boards = [];
      
      if (agileManager.getBoards) {
        boards = await agileManager.getBoards();
      } else {
        // Return mock board data
        boards = [
          {
            id: 'board-1',
            name: 'Development Board',
            columns: ['To Do', 'In Progress', 'Done'],
            createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date().toISOString()
          }
        ];
      }
      
      res.json({
        success: true,
        data: boards,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching boards:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch boards',
        message: (error as Error).message
      });
    }
  });

  // Create a new board
  app.post('/api/agile/boards', async (req: Request, res: Response) => {
    try {
      const { name, columns } = req.body;
      
      if (!name || !columns || !Array.isArray(columns)) {
        return res.status(400).json({
          success: false,
          error: 'Board name and columns are required'
        });
      }
      
      let board = null;
      
      if (agileManager.createBoard) {
        board = await agileManager.createBoard({ name, columns });
      } else {
        // Return mock created board
        board = {
          id: `board-${Date.now()}`,
          name,
          columns,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        };
      }
      
      res.status(201).json({
        success: true,
        data: board,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error creating board:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to create board',
        message: (error as Error).message
      });
    }
  });

  // Get backlog items
  app.get('/api/agile/backlog', async (req: Request, res: Response) => {
    try {
      const options = {
        includeEstimates: req.query.includeEstimates === 'true',
        maxItems: Number(req.query.maxItems) || 20
      };
      
      let backlog = [];
      
      if (agileManager.getBacklogItems) {
        backlog = await agileManager.getBacklogItems(options);
      } else {
        // Return mock backlog data
        backlog = [
          {
            id: 'story-10',
            title: 'High priority feature',
            priority: 'high',
            storyPoints: 8,
            status: 'backlog',
            createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString()
          }
        ];
      }
      
      res.json({
        success: true,
        data: backlog,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching backlog:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch backlog',
        message: (error as Error).message
      });
    }
  });

  // Estimate a story
  app.post('/api/agile/estimate', async (req: Request, res: Response) => {
    try {
      const { storyId, estimates, finalEstimate } = req.body;
      
      let result = null;
      
      if (agileManager.estimateStory) {
        result = await agileManager.estimateStory(storyId, req.body);
      } else {
        // Return mock estimation result
        result = {
          storyId,
          estimate: finalEstimate || 5,
          confidence: 85,
          estimatedAt: new Date().toISOString()
        };
      }
      
      res.json({
        success: true,
        data: result,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error estimating story:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to estimate story',
        message: (error as Error).message
      });
    }
  });

  // Get team capacity for sprint
  app.get('/api/agile/capacity/:sprintId', async (req: Request, res: Response) => {
    try {
      const { sprintId } = req.params;
      
      let capacity = null;
      
      if (agileManager.getTeamCapacity) {
        capacity = await agileManager.getTeamCapacity(sprintId);
      } else {
        // Return mock capacity data
        capacity = {
          sprintId,
          totalHours: 320,
          totalStoryPoints: 40,
          teamMembers: [
            { name: 'John Doe', hours: 80, storyPoints: 10 },
            { name: 'Jane Smith', hours: 80, storyPoints: 10 }
          ],
          utilization: 85
        };
      }
      
      res.json({
        success: true,
        data: capacity,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching team capacity:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch team capacity',
        message: (error as Error).message
      });
    }
  });

  // Generate sprint report
  app.get('/api/agile/report/:sprintId', async (req: Request, res: Response) => {
    try {
      const { sprintId } = req.params;
      const options = {
        includeMetrics: req.query.includeMetrics === 'true',
        includeStories: true,
        includeRetrospective: false,
        format: req.query.format as string || 'detailed'
      };
      
      let report = null;
      
      if (agileManager.generateSprintReport) {
        report = await agileManager.generateSprintReport(sprintId, options);
      } else {
        // Return mock report data
        report = {
          sprint: { id: sprintId, name: 'Sprint 1' },
          metrics: { velocity: 25, completionRate: 85 },
          highlights: ['Completed authentication'],
          issues: ['Technical debt in payment module'],
          generatedAt: new Date().toISOString()
        };
      }
      
      res.json({
        success: true,
        data: report,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error generating sprint report:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to generate sprint report',
        message: (error as Error).message
      });
    }
  });

  // Epic endpoints
  
  // Get all epics
  app.get('/api/agile/epics', async (req: Request, res: Response) => {
    try {
      const { status, priority, limit = 100, offset = 0 } = req.query;
      
      let epics = [];
      
      if (agileManager.getEpics) {
        const filter: any = {};
        if (status) filter.status = status;
        if (priority) filter.priority = priority;
        epics = await agileManager.getEpics(filter);
        
        // Apply pagination
        const startIndex = Number(offset);
        const endIndex = startIndex + Number(limit);
        epics = epics.slice(startIndex, endIndex);
      } else {
        // Return mock epics for dashboard testing
        epics = [
          {
            id: 'EPIC-001',
            title: 'User Management System',
            description: 'Complete user authentication and authorization system',
            status: 'active',
            priority: 'high',
            goals: [
              'Secure authentication with JWT',
              'Role-based access control',
              'User profile management',
              'Password reset functionality'
            ],
            owner: 'John Doe',
            storyIds: ['STORY-001', 'STORY-002', 'STORY-003'],
            progress: 40,
            completedStories: 1,
            createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
            updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
            metadata: {
              businessValue: 'Essential for platform security and user experience',
              targetUsers: 'All platform users',
              estimatedEffort: '3-4 weeks'
            }
          },
          {
            id: 'EPIC-002',
            title: 'Payment Integration',
            description: 'Integrate multiple payment providers and subscription management',
            status: 'planned',
            priority: 'high',
            goals: [
              'Stripe integration',
              'PayPal support',
              'Subscription management',
              'Invoice generation'
            ],
            owner: 'Jane Smith',
            storyIds: [],
            progress: 0,
            completedStories: 0,
            createdAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000),
            updatedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
            metadata: {
              businessValue: 'Revenue generation and monetization',
              targetUsers: 'Premium users and businesses',
              risks: 'PCI compliance requirements'
            }
          },
          {
            id: 'EPIC-003',
            title: 'Analytics Dashboard',
            description: 'Comprehensive analytics and reporting for users',
            status: 'active',
            priority: 'medium',
            goals: [
              'Real-time metrics',
              'Custom reports',
              'Data export functionality'
            ],
            owner: 'Bob Johnson',
            storyIds: ['STORY-004', 'STORY-005'],
            progress: 60,
            completedStories: 3,
            createdAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000),
            updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
          }
        ];
        
        // Apply filters to mock data
        if (status) {
          epics = epics.filter(epic => epic.status === status);
        }
        if (priority) {
          epics = epics.filter(epic => epic.priority === priority);
        }
      }
      
      res.json({
        success: true,
        data: { epics },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching epics:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch epics',
        message: (error as Error).message
      });
    }
  });

  // Get specific epic details
  app.get('/api/agile/epic/:id', async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      
      let epic = null;
      
      if (agileManager.getEpic) {
        epic = await agileManager.getEpic(id);
      } else {
        // Return mock epic
        epic = {
          id,
          title: 'User Management System',
          description: 'Complete user authentication and authorization system',
          status: 'active',
          priority: 'high',
          goals: [
            'Secure authentication with JWT',
            'Role-based access control',
            'User profile management',
            'Password reset functionality'
          ],
          owner: 'John Doe',
          storyIds: ['STORY-001', 'STORY-002', 'STORY-003'],
          progress: 40,
          completedStories: 1,
          createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
          updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
          metadata: {
            businessValue: 'Essential for platform security and user experience',
            targetUsers: 'All platform users',
            estimatedEffort: '3-4 weeks',
            hasDependencies: true,
            dependencyDetails: 'Requires database schema to be finalized'
          }
        };
      }
      
      if (!epic) {
        return res.status(404).json({
          success: false,
          error: 'Epic not found',
          epicId: id
        });
      }
      
      res.json({
        success: true,
        data: epic,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error(`📋 Error fetching epic ${req.params.id}:`, error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch epic details',
        message: (error as Error).message
      });
    }
  });

  // Get stories for a specific epic
  app.get('/api/agile/stories', async (req: Request, res: Response) => {
    try {
      const { 
        sprintId, 
        epicId,
        status, 
        assignee, 
        priority,
        limit = 50,
        offset = 0 
      } = req.query;
      
      const filters = {
        sprintId,
        epicId,
        status,
        assignee,
        priority,
        limit: Number(limit),
        offset: Number(offset)
      };
      
      let stories = [];
      
      if (agileManager.getBacklog) {
        // Use the available getBacklog method to get all stories
        const allStories = await agileManager.getBacklog();
        stories = allStories;
        
        // Apply filters
        if (sprintId) {
          stories = stories.filter((story: any) => story.sprintId === sprintId);
        }
        if (epicId) {
          stories = stories.filter((story: any) => story.epic === epicId);
        }
        if (status) {
          stories = stories.filter((story: any) => story.status === status);
        }
        if (assignee) {
          stories = stories.filter((story: any) => story.assignee === assignee);
        }
        if (priority) {
          stories = stories.filter((story: any) => story.priority === priority);
        }
        
        // Apply pagination
        const startIndex = Number(offset);
        const endIndex = startIndex + Number(limit);
        stories = stories.slice(startIndex, endIndex);
      } else {
        // Return mock data
        stories = [
          {
            id: 'STORY-001',
            title: 'User Authentication System',
            description: 'Implement secure user login and registration with JWT tokens',
            status: 'done',
            storyPoints: 8,
            assignee: 'John Doe',
            priority: 'high',
            sprintId: 'SPRINT-001',
            epic: epicId || 'EPIC-001',
            tags: ['authentication', 'security'],
            createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'STORY-002',
            title: 'Database Schema Setup',
            description: 'Create initial database tables and relationships for user management',
            status: 'in_progress',
            storyPoints: 5,
            assignee: 'Jane Smith',
            priority: 'high',
            sprintId: 'SPRINT-001',
            epic: epicId || 'EPIC-001',
            tags: ['database', 'setup'],
            createdAt: new Date(Date.now() - 9 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'STORY-003',
            title: 'API Rate Limiting',
            description: 'Implement rate limiting middleware for API endpoints',
            status: 'todo',
            storyPoints: 3,
            assignee: 'Bob Johnson',
            priority: 'medium',
            sprintId: 'SPRINT-001',
            epic: epicId || 'EPIC-001',
            tags: ['api', 'security', 'middleware'],
            createdAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
          }
        ];
        
        // Apply filters to mock data
        if (status) {
          stories = stories.filter(story => story.status === status);
        }
        if (assignee) {
          stories = stories.filter(story => story.assignee.toLowerCase().includes((assignee as string).toLowerCase()));
        }
        if (priority) {
          stories = stories.filter(story => story.priority === priority);
        }
        if (sprintId) {
          stories = stories.filter(story => story.sprintId === sprintId);
        }
        if (epicId) {
          stories = stories.filter(story => story.epic === epicId);
        }
      }
      
      res.json({
        success: true,
        data: { stories },
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching stories:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch stories',
        message: (error as Error).message
      });
    }
  });

  // Add alias endpoint for dashboard compatibility
  app.get('/api/agile/sprint/:id', async (req: Request, res: Response) => {
    try {
      const { id } = req.params;
      
      let sprint = null;
      
      if (agileManager.getSprint) {
        sprint = await agileManager.getSprint(id);
      }
      
      if (!sprint) {
        return res.status(404).json({
          success: false,
          error: 'Sprint not found',
          sprintId: id
        });
      }

      // Get stories for this sprint
      let stories = [];
      if (agileManager.getBacklog) {
        const allStories = await agileManager.getBacklog();
        stories = allStories.filter((story: any) => story.sprintId === id);
      }

      // Calculate metrics for dashboard
      const totalStoryPoints = stories.reduce((sum: number, story: any) => sum + (story.storyPoints || 0), 0);
      const completedStoryPoints = stories
        .filter((story: any) => story.status === 'done')
        .reduce((sum: number, story: any) => sum + (story.storyPoints || 0), 0);
      const completedStories = stories.filter((story: any) => story.status === 'done').length;

      const sprintData = {
        ...sprint,
        storyPointsPlanned: totalStoryPoints,
        storyPointsCompleted: completedStoryPoints,
        storiesTotal: stories.length,
        storiesCompleted: completedStories,
        stories: stories
      };
      
      res.json({
        success: true,
        data: sprintData,
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      console.error('📋 Error fetching sprint:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to fetch sprint',
        message: (error as Error).message
      });
    }
  });
}