import express from 'express';
import { authenticateToken, optionalAuth } from '../middleware/auth.js';
import Project from '../models/Project.js';

const router = express.Router();

/**
 * PHASE 2: MCP Tools Integration
 * Provides API endpoints for Model Context Protocol tool execution
 * Tools include: project analysis, token extraction, theme generation, component auditing
 */

// List available MCP tools
router.get('/tools', optionalAuth, async (req, res, next) => {
  try {
    const tools = [
      {
        name: 'dss-analyze-project',
        description: 'Analyze codebase for design patterns and component usage',
        params: {
          projectPath: 'string (required) - Path to project directory',
          depth: 'number (optional) - Analysis depth (1-3)'
        }
      },
      {
        name: 'dss-extract-tokens',
        description: 'Extract design tokens from CSS, SCSS, Tailwind, or JSON sources',
        params: {
          path: 'string (required) - Path to token source files',
          sources: 'array (optional) - Source types: css, scss, tailwind, json'
        }
      },
      {
        name: 'dss-generate-theme',
        description: 'Generate theme files from design tokens using style-dictionary',
        params: {
          tokens: 'object (required) - Design tokens configuration',
          format: 'string (required) - Output format: css, scss, json, js',
          themeName: 'string (optional) - Theme name for generation'
        }
      },
      {
        name: 'dss-audit-components',
        description: 'Audit React components for design system adoption',
        params: {
          path: 'string (required) - Path to component directory',
          strict: 'boolean (optional) - Enable strict validation'
        }
      },
      {
        name: 'dss-sync-figma',
        description: 'Synchronize design tokens from Figma',
        params: {
          fileKey: 'string (required) - Figma file key from URL',
          figmaToken: 'string (required) - Figma API token'
        }
      }
    ];

    res.status(200).json({
      status: 'success',
      code: 'MCP_TOOLS_LIST',
      message: 'Available MCP tools',
      data: { tools }
    });
  } catch (error) {
    next(error);
  }
});

// Execute a specific MCP tool
router.post('/tools/:name/execute', authenticateToken, async (req, res, next) => {
  try {
    const { name } = req.params;
    const params = req.body;

    // Validate tool exists
    const validTools = [
      'dss-analyze-project',
      'dss-extract-tokens',
      'dss-generate-theme',
      'dss-audit-components',
      'dss-sync-figma'
    ];

    if (!validTools.includes(name)) {
      return res.status(404).json({
        status: 'error',
        code: 'TOOL_NOT_FOUND',
        message: `Tool '${name}' not found`,
        data: null
      });
    }

    // Log execution attempt
    console.log(`[MCP] Executing tool: ${name} for user: ${req.user.id}`);

    // Simulate tool execution (actual execution would be handled by DSS Claude Plugin)
    const result = {
      toolName: name,
      status: 'pending',
      executedAt: new Date().toISOString(),
      estimatedDuration: '30-60 seconds',
      message: `Tool '${name}' execution queued. Check project discovery tab for results.`,
      webhookUrl: `${process.env.API_BASE_URL || 'http://localhost:3001'}/api/mcp/callback`
    };

    res.status(202).json({
      status: 'success',
      code: 'TOOL_EXECUTION_QUEUED',
      message: 'Tool execution queued',
      data: result
    });
  } catch (error) {
    next(error);
  }
});

// Discover project using MCP analysis
router.post('/discover_project', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, path, depth = 2 } = req.body;

    if (!projectId && !path) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Either projectId or path is required',
        data: null
      });
    }

    // Get project if projectId provided
    let project = null;
    if (projectId) {
      project = await Project.findOne({
        where: { id: projectId, userId: req.user.id }
      });

      if (!project) {
        return res.status(404).json({
          status: 'error',
          code: 'PROJECT_NOT_FOUND',
          message: 'Project not found',
          data: null
        });
      }
    }

    const discoveryRequest = {
      projectId: project?.id || null,
      projectPath: path || project?.sourcePath || null,
      userId: req.user.id,
      analysisDepth: Math.min(depth, 3),
      timestamp: new Date().toISOString(),
      status: 'queued'
    };

    // Queue for DSS Claude Plugin to process
    console.log(`[MCP] Discovery requested for project: ${projectId || path}`);

    res.status(202).json({
      status: 'success',
      code: 'DISCOVERY_QUEUED',
      message: 'Project discovery analysis queued',
      data: {
        discoveryId: `discovery_${Date.now()}`,
        estimatedTime: '2-5 minutes',
        pollEndpoint: `/api/discovery/activity`
      }
    });
  } catch (error) {
    next(error);
  }
});

// Get quick wins for a project
router.post('/get_quick_wins', authenticateToken, async (req, res, next) => {
  try {
    const { projectId, path } = req.body;

    if (!projectId && !path) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Either projectId or path is required',
        data: null
      });
    }

    // Get project if projectId provided
    let project = null;
    if (projectId) {
      project = await Project.findOne({
        where: { id: projectId, userId: req.user.id }
      });

      if (!project) {
        return res.status(404).json({
          status: 'error',
          code: 'PROJECT_NOT_FOUND',
          message: 'Project not found',
          data: null
        });
      }
    }

    console.log(`[MCP] Quick wins analysis requested for project: ${projectId || path}`);

    // Return template for quick wins
    const quickWinsRequest = {
      projectPath: path || project?.sourcePath || null,
      userId: req.user.id,
      timestamp: new Date().toISOString(),
      status: 'queued'
    };

    res.status(202).json({
      status: 'success',
      code: 'QUICK_WINS_ANALYSIS_QUEUED',
      message: 'Quick wins analysis queued',
      data: {
        analysisId: `quickwins_${Date.now()}`,
        expectedWins: [
          'Component centralization',
          'Token standardization',
          'Color palette reduction',
          'Typography consolidation'
        ],
        estimatedTime: '1-3 minutes',
        pollEndpoint: `/api/discovery/stats`
      }
    });
  } catch (error) {
    next(error);
  }
});

// Webhook callback for tool execution results
router.post('/callback', express.json(), async (req, res, next) => {
  try {
    const { toolName, status, data, projectId } = req.body;

    console.log(`[MCP] Tool callback received: ${toolName} - ${status}`);

    // Store results or emit notification
    if (projectId) {
      const project = await Project.findByPk(projectId);
      if (project) {
        // Update project with discovery results if available
        if (toolName === 'dss-analyze-project' && data) {
          await project.update({
            settings: {
              ...project.settings,
              lastDiscovery: {
                timestamp: new Date().toISOString(),
                analysis: data
              }
            }
          });
        }
      }
    }

    res.status(200).json({
      status: 'success',
      code: 'CALLBACK_ACKNOWLEDGED',
      message: 'Tool callback processed',
      data: null
    });
  } catch (error) {
    next(error);
  }
});

export default router;
