// routes/ai-streaming.routes.js
const express = require('express');
const router = express.Router();
const AIStreamingService = require('../services/ai-streaming.service');
const database = require('../config/database');

const aiStreamingService = new AIStreamingService();

// WebSocket streaming endpoint for AI analysis
router.get('/repository/:id/ai-stream', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const {
      file_types = 'auto', // Auto-detect all file types
      max_size = 3000000, // Increased to 3MB to include larger files
      include_binary = 'true', // Changed to true to include binary files
      directory_filter = '',
      exclude_patterns = 'node_modules,dist,build,.git,coverage',
      chunk_size = 'auto' // Auto-calculate optimal chunk size
    } = req.query;

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found'
      });
    }

    // Parse parameters with auto-detection
    let fileTypesArray;
    let chunkSize;
    
    if (file_types === 'auto') {
      // Auto-detect file types from repository
      fileTypesArray = await aiStreamingService.getAvailableFileTypes(repositoryId);
    } else {
      fileTypesArray = file_types.split(',').map(t => t.trim());
    }
    
    if (chunk_size === 'auto') {
      // Auto-calculate optimal chunk size based on total files
      const totalFiles = await aiStreamingService.getRepositoryFilesCount(repositoryId, {
        fileTypes: fileTypesArray,
        maxSize: parseInt(max_size),
        includeBinary: include_binary === 'true',
        directoryFilter: directory_filter,
        excludePatterns: exclude_patterns.split(',').map(p => p.trim())
      });
      chunkSize = aiStreamingService.calculateOptimalChunkSize(totalFiles);
    } else {
      chunkSize = parseInt(chunk_size);
    }
    
    const maxSizeBytes = parseInt(max_size);
    const includeBinaryFiles = include_binary === 'true';
    const excludePatternsArray = exclude_patterns.split(',').map(p => p.trim());

    // Get total files count
    const totalFiles = await aiStreamingService.getRepositoryFilesCount(repositoryId, {
      fileTypes: fileTypesArray,
      maxSize: maxSizeBytes,
      includeBinary: includeBinaryFiles,
      directoryFilter: directory_filter,
      excludePatterns: excludePatternsArray
    });

    if (totalFiles === 0) {
      return res.status(404).json({
        success: false,
        message: 'No files found matching the criteria'
      });
    }

    // Calculate total chunks
    const totalChunks = Math.ceil(totalFiles / chunkSize);

    // Create streaming session
    const sessionId = aiStreamingService.createStreamingSession(repositoryId, {
      fileTypes: fileTypesArray,
      maxSize: maxSizeBytes,
      includeBinary: includeBinaryFiles,
      directoryFilter: directory_filter,
      excludePatterns: excludePatternsArray,
      chunkSize: chunkSize
    });

    // Update session with total info
    aiStreamingService.updateStreamingSession(sessionId, {
      totalFiles,
      totalChunks,
      status: 'ready'
    });

    // Get repository info
    const repositoryInfo = await aiStreamingService.getRepositoryInfo(repositoryId);

    // Set headers for streaming
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Streaming-Session-ID', sessionId);

    // Send initial response
    res.write(JSON.stringify({
      success: true,
      session_id: sessionId,
      repository_info: {
        id: repositoryInfo.id,
        name: repositoryInfo.name,
        full_name: repositoryInfo.full_name,
        description: repositoryInfo.description,
        language: repositoryInfo.language,
        size: repositoryInfo.size,
        local_path: repositoryInfo.local_path
      },
      streaming_config: {
        total_files: totalFiles,
        total_chunks: totalChunks,
        chunk_size: chunkSize,
        file_types: fileTypesArray,
        max_size_bytes: maxSizeBytes,
        include_binary: includeBinaryFiles,
        directory_filter: directory_filter,
        exclude_patterns: excludePatternsArray
      },
      status: 'ready'
    }) + '\n');

    // Process files in chunks
    let currentChunk = 0;
    let processedFiles = 0;

    while (currentChunk < totalChunks) {
      try {
        const offset = currentChunk * chunkSize;
        const files = await aiStreamingService.getFilesChunk(repositoryId, offset, chunkSize, {
          fileTypes: fileTypesArray,
          maxSize: maxSizeBytes,
          includeBinary: includeBinaryFiles,
          directoryFilter: directory_filter,
          excludePatterns: excludePatternsArray
        });

        if (files.length === 0) {
          break;
        }

        // Process chunk
        const chunkResult = await aiStreamingService.processFilesChunk(
          files, 
          currentChunk + 1, 
          totalChunks
        );

        processedFiles += chunkResult.files_processed;

        // Update session
        aiStreamingService.updateStreamingSession(sessionId, {
          currentChunk: currentChunk + 1,
          processedFiles,
          status: 'streaming'
        });

        // Send chunk data
        res.write(JSON.stringify({
          type: 'chunk',
          chunk_data: chunkResult,
          progress: {
            current_chunk: currentChunk + 1,
            total_chunks: totalChunks,
            processed_files: processedFiles,
            total_files: totalFiles,
            percentage: Math.round((processedFiles / totalFiles) * 100)
          },
          timestamp: new Date().toISOString()
        }) + '\n');

        currentChunk++;

        // Small delay to prevent overwhelming the client
        await new Promise(resolve => setTimeout(resolve, 50));

      } catch (error) {
        console.error(`Error processing chunk ${currentChunk + 1}:`, error);
        
        // Send error for this chunk
        res.write(JSON.stringify({
          type: 'error',
          chunk_number: currentChunk + 1,
          error: error.message,
          timestamp: new Date().toISOString()
        }) + '\n');

        currentChunk++;
      }
    }

    // Send completion message
    res.write(JSON.stringify({
      type: 'complete',
      session_id: sessionId,
      total_files_processed: processedFiles,
      total_chunks_processed: currentChunk,
      processing_time_ms: Date.now() - aiStreamingService.getStreamingSession(sessionId).startTime,
      timestamp: new Date().toISOString()
    }) + '\n');

    // Clean up session
    aiStreamingService.removeStreamingSession(sessionId);

    res.end();

  } catch (error) {
    console.error('Error in AI streaming:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to stream files for AI analysis'
    });
  }
});

// Get streaming session status
router.get('/streaming-session/:sessionId', (req, res) => {
  try {
    const { sessionId } = req.params;
    const session = aiStreamingService.getStreamingSession(sessionId);

    if (!session) {
      return res.status(404).json({
        success: false,
        message: 'Streaming session not found'
      });
    }

    res.json({
      success: true,
      session: {
        session_id: sessionId,
        repository_id: session.repositoryId,
        status: session.status,
        current_chunk: session.currentChunk,
        total_chunks: session.totalChunks,
        total_files: session.totalFiles,
        processed_files: session.processedFiles,
        progress_percentage: session.totalFiles > 0 ? 
          Math.round((session.processedFiles / session.totalFiles) * 100) : 0,
        start_time: new Date(session.startTime).toISOString(),
        last_activity: new Date(session.lastActivity).toISOString()
      }
    });

  } catch (error) {
    console.error('Error getting streaming session:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to get streaming session status'
    });
  }
});

// Cancel streaming session
router.delete('/streaming-session/:sessionId', (req, res) => {
  try {
    const { sessionId } = req.params;
    const session = aiStreamingService.getStreamingSession(sessionId);

    if (!session) {
      return res.status(404).json({
        success: false,
        message: 'Streaming session not found'
      });
    }

    aiStreamingService.removeStreamingSession(sessionId);

    res.json({
      success: true,
      message: 'Streaming session cancelled successfully'
    });

  } catch (error) {
    console.error('Error cancelling streaming session:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to cancel streaming session'
    });
  }
});

// Get active streaming sessions
router.get('/streaming-sessions', (req, res) => {
  try {
    const sessions = Array.from(aiStreamingService.activeStreams.entries()).map(([sessionId, session]) => ({
      session_id: sessionId,
      repository_id: session.repositoryId,
      status: session.status,
      current_chunk: session.currentChunk,
      total_chunks: session.totalChunks,
      total_files: session.totalFiles,
      processed_files: session.processedFiles,
      progress_percentage: session.totalFiles > 0 ? 
        Math.round((session.processedFiles / session.totalFiles) * 100) : 0,
      start_time: new Date(session.startTime).toISOString(),
      last_activity: new Date(session.lastActivity).toISOString()
    }));

    res.json({
      success: true,
      active_sessions: sessions.length,
      sessions: sessions
    });

  } catch (error) {
    console.error('Error getting streaming sessions:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to get streaming sessions'
    });
  }
});

// Cleanup old sessions
router.post('/cleanup-sessions', (req, res) => {
  try {
    aiStreamingService.cleanupOldSessions();
    
    res.json({
      success: true,
      message: 'Old streaming sessions cleaned up successfully'
    });

  } catch (error) {
    console.error('Error cleaning up sessions:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to cleanup sessions'
    });
  }
});

// Debug endpoint to check diff content availability
router.get('/repository/:id/commit/:commitId/debug', async (req, res) => {
  try {
    const { id: repositoryId, commitId } = req.params;
    
    console.log(`🔍 Debugging diff content for repository ${repositoryId}, commit ${commitId}`);
    
    // Check if commit exists in database
    const commitQuery = `
      SELECT 
        id,
        repository_id,
        commit_sha,
        message,
        author_name,
        author_email,
        committed_at,
        created_at
      FROM repository_commit_details
      WHERE commit_sha = $1
    `;
    
    const commitResult = await database.query(commitQuery, [commitId]);
    
    if (commitResult.rows.length === 0) {
      return res.json({
        success: false,
        message: 'Commit not found in database',
        repository_id: repositoryId,
        commit_id: commitId,
        debug_info: {
          commit_exists: false,
          diff_content_exists: false,
          local_file_exists: false
        }
      });
    }
    
    const commit = commitResult.rows[0];
    
    // Check if diff content exists in database
    const diffQuery = `
      SELECT 
        id,
        commit_id,
        diff_header,
        diff_size_bytes,
        storage_type,
        external_storage_path,
        file_path,
        change_type,
        processing_status,
        created_at
      FROM diff_contents
      WHERE commit_id = $1
    `;
    
    const diffResult = await database.query(diffQuery, [commit.id]);
    
    // Check if local file exists
    const fs = require('fs');
    const path = require('path');
    const diffDir = process.env.DIFF_STORAGE_DIR || '/home/tech4biz/Desktop/today work/git-diff';
    const commitDir = path.join(diffDir, commitId);
    const diffFilePath = path.join(diffDir, `${commitId}.diff`);
    
    // Check for commit directory structure (new format)
    const commitDirExists = fs.existsSync(commitDir);
    let localFileExists = false;
    let localFiles = [];
    
    if (commitDirExists) {
      const files = fs.readdirSync(commitDir);
      localFiles = files.filter(file => file.endsWith('.diff'));
      localFileExists = localFiles.length > 0;
    } else {
      // Check for single diff file (old format)
      localFileExists = fs.existsSync(diffFilePath);
    }
    
    // Check file changes
    const fileQuery = `
      SELECT 
        id,
        commit_id,
        file_path,
        change_type,
        created_at
      FROM repository_commit_files
      WHERE commit_id = $1
    `;
    
    const fileResult = await database.query(fileQuery, [commit.id]);
    
    res.json({
      success: true,
      repository_id: repositoryId,
      commit_id: commitId,
      debug_info: {
        commit_exists: true,
        commit_details: commit,
        diff_content_exists: diffResult.rows.length > 0,
        diff_contents: diffResult.rows,
        local_file_exists: localFileExists,
        commit_dir_exists: commitDirExists,
        commit_dir_path: commitDir,
        local_files: localFiles,
        single_file_path: diffFilePath,
        file_changes_count: fileResult.rows.length,
        file_changes: fileResult.rows
      }
    });
    
  } catch (error) {
    console.error('Error in debug endpoint:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to debug diff content',
      repository_id: req.params.id,
      commit_id: req.params.commitId
    });
  }
});

// Single endpoint for incremental diff analysis
router.get('/repository/:id/commit/:commitId/diff-analysis', async (req, res) => {
  try {
    const { id: repositoryId, commitId } = req.params;
    const { 
      include_context = 'true',
      analysis_type = 'auto', // 'auto', 'full', 'incremental'
      stream = 'false'
    } = req.query;

    console.log(`🔍 Analyzing diff for repository ${repositoryId}, commit ${commitId}`);

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name, owner_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found',
        repository_id: repositoryId
      });
    }

    const repository = repoResult.rows[0];
    const repositoryName = repository.repository_name;
    const ownerName = repository.owner_name;

    // Get repository storage path
    const storageQuery = 'SELECT local_path FROM repository_storage WHERE repository_id = $1';
    const storageResult = await database.query(storageQuery, [repositoryId]);
    
    if (storageResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not stored locally',
        repository_id: repositoryId
      });
    }

    const repoPath = storageResult.rows[0].local_path;

    // Check if diff content exists locally
    const actualDiffContent = await aiStreamingService.getActualDiffContent(commitId);
    
    if (!actualDiffContent) {
      return res.status(404).json({
        success: false,
        message: 'No diff content found for this commit',
        repository_id: repositoryId,
        commit_id: commitId
      });
    }

    // Get simple file changes (NO FILE CREATION)
    const fileChanges = await aiStreamingService.getSimpleFileChanges(commitId);

    // Simple response
    const response = {
      success: true,
      repository_id: repositoryId,
      commit_id: commitId,
      files: fileChanges,
      diff_content: actualDiffContent
    };

    // Handle streaming if requested
    if (stream === 'true') {
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Connection', 'keep-alive');
      
      // Send initial response
      res.write(JSON.stringify({
        ...response,
        stream_status: 'started'
      }) + '\n');

      // Stream analysis chunks
      const chunks = await aiStreamingService.streamAnalysisChunks(analysis, diffMetadata);
      for (const chunk of chunks) {
        res.write(JSON.stringify({
          type: 'analysis_chunk',
          chunk_data: chunk,
          timestamp: new Date().toISOString()
        }) + '\n');
      }

      // Send completion
      res.write(JSON.stringify({
        type: 'complete',
        stream_status: 'finished',
        total_chunks: chunks.length,
        timestamp: new Date().toISOString()
      }) + '\n');

      res.end();
    } else {
      res.json(response);
    }

  } catch (error) {
    console.error('Error in diff analysis:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to analyze diff',
      repository_id: req.params.id,
      commit_id: req.params.commitId
    });
  }
});

// Get stored diffs for a repository
router.get('/repository/:id/diffs', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { limit = 10, offset = 0 } = req.query;

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found'
      });
    }

    const diffs = await aiStreamingService.getRepositoryDiffs(repositoryId, {
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      success: true,
      repository_id: repositoryId,
      diffs: diffs,
      total: diffs.length
    });

  } catch (error) {
    console.error('Error getting repository diffs:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to get repository diffs'
    });
  }
});

// AI analysis for diff content
router.get('/repository/:id/diff-analysis', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { diff_id, include_context = 'true' } = req.query;

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found'
      });
    }

    // Get diff analysis
    const analysis = await aiStreamingService.analyzeDiffContent(repositoryId, diff_id, {
      includeContext: include_context === 'true'
    });

    res.json({
      success: true,
      repository_id: repositoryId,
      analysis: analysis
    });

  } catch (error) {
    console.error('Error analyzing diff content:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to analyze diff content'
    });
  }
});

// Stream diff analysis (similar to ai-stream but for diffs)
router.get('/repository/:id/diff-stream', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { diff_id, include_context = 'true' } = req.query;

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found'
      });
    }

    // Create streaming session for diff analysis
    const sessionId = aiStreamingService.createDiffStreamingSession(repositoryId, {
      diffId: diff_id,
      includeContext: include_context === 'true'
    });

    // Set headers for streaming
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Streaming-Session-ID', sessionId);

    // Send initial response
    res.write(JSON.stringify({
      success: true,
      session_id: sessionId,
      repository_id: repositoryId,
      diff_id: diff_id,
      status: 'ready'
    }) + '\n');

    // Process diff analysis
    const analysisResult = await aiStreamingService.streamDiffAnalysis(sessionId, repositoryId, diff_id, {
      includeContext: include_context === 'true'
    });

    // Send analysis chunks
    for (const chunk of analysisResult.chunks) {
      res.write(JSON.stringify({
        type: 'analysis_chunk',
        chunk_data: chunk,
        timestamp: new Date().toISOString()
      }) + '\n');
    }

    // Send completion message
    res.write(JSON.stringify({
      type: 'complete',
      session_id: sessionId,
      total_chunks: analysisResult.chunks.length,
      processing_time_ms: analysisResult.processingTime,
      timestamp: new Date().toISOString()
    }) + '\n');

    // Clean up session
    aiStreamingService.removeStreamingSession(sessionId);

    res.end();

  } catch (error) {
    console.error('Error in diff streaming:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to stream diff analysis'
    });
  }
});

// ==================== BULK COMMIT ANALYSIS ENDPOINTS ====================

// Bulk commit analysis endpoint
router.post('/repository/:id/bulk-analysis', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { 
      commit_ids = [],
      analysis_type = 'bulk',
      include_content = 'true',
      stream = 'false'
    } = req.body;

    console.log(`🔍 Bulk analysis for repository ${repositoryId} with ${commit_ids.length} commits`);

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name, owner_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found',
        repository_id: repositoryId
      });
    }

    // Validate commit IDs
    if (!Array.isArray(commit_ids) || commit_ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'commit_ids must be a non-empty array',
        repository_id: repositoryId
      });
    }

    // Limit the number of commits to prevent overload
    const maxCommits = 50;
    if (commit_ids.length > maxCommits) {
      return res.status(400).json({
        success: false,
        message: `Maximum ${maxCommits} commits allowed per request`,
        repository_id: repositoryId,
        requested_commits: commit_ids.length
      });
    }

    // Get bulk commit details
    const commitResults = await aiStreamingService.getBulkCommitDetails(commit_ids);
    
    // Read diff files in batch
    const enrichedResults = await aiStreamingService.batchReadDiffFiles(commitResults);
    
    // Get analysis summary
    const summary = await aiStreamingService.getBulkAnalysisSummary(enrichedResults);
    
    // Process for AI analysis
    const aiInputs = await aiStreamingService.processBulkCommitsForAI(enrichedResults);

    // Prepare response - only include ai_inputs to avoid duplication
    const response = {
      success: true,
      repository_id: repositoryId,
      analysis_type: analysis_type,
      summary: summary,
      ai_ready_commits: aiInputs.length,
      ai_inputs: include_content === 'true' ? aiInputs : []
    };

    // Handle streaming if requested
    if (stream === 'true') {
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Connection', 'keep-alive');
      res.write(JSON.stringify(response) + '\n');
      res.end();
    } else {
      res.json(response);
    }

  } catch (error) {
    console.error('Error in bulk analysis endpoint:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to perform bulk analysis',
      repository_id: req.params.id
    });
  }
});

// Get bulk analysis status
router.get('/repository/:id/bulk-analysis/status', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { commit_ids } = req.query;

    console.log(`📊 Getting bulk analysis status for repository ${repositoryId}`);

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found',
        repository_id: repositoryId
      });
    }

    // Parse commit IDs from query string
    const commitIds = commit_ids ? commit_ids.split(',') : [];
    
    if (commitIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'commit_ids parameter is required',
        repository_id: repositoryId
      });
    }

    // Get status for each commit
    const statusResults = [];
    
    for (const commitId of commitIds) {
      try {
        // Check if commit exists in database
        const commitQuery = `
          SELECT id, commit_sha, message, committed_at
          FROM repository_commit_details 
          WHERE id = $1
        `;
        
        const commitResult = await database.query(commitQuery, [commitId]);
        
        if (commitResult.rows.length === 0) {
          statusResults.push({
            commitId: commitId,
            status: 'not_found',
            message: 'Commit not found in database'
          });
          continue;
        }

        // Check if diff content exists
        const diffQuery = `
          SELECT COUNT(*) as count
          FROM diff_contents 
          WHERE commit_id = $1
        `;
        
        const diffResult = await database.query(diffQuery, [commitId]);
        const hasDiffContent = parseInt(diffResult.rows[0].count) > 0;

        statusResults.push({
          commitId: commitId,
          status: 'found',
          hasDiffContent: hasDiffContent,
          commitDetails: commitResult.rows[0]
        });

      } catch (error) {
        console.error(`Error checking status for commit ${commitId}:`, error);
        statusResults.push({
          commitId: commitId,
          status: 'error',
          message: error.message
        });
      }
    }

    // Calculate summary
    const summary = {
      total_commits: statusResults.length,
      found_commits: statusResults.filter(r => r.status === 'found').length,
      not_found_commits: statusResults.filter(r => r.status === 'not_found').length,
      error_commits: statusResults.filter(r => r.status === 'error').length,
      commits_with_diff: statusResults.filter(r => r.hasDiffContent).length
    };

    res.json({
      success: true,
      repository_id: repositoryId,
      summary: summary,
      commits: statusResults
    });

  } catch (error) {
    console.error('Error in bulk analysis status endpoint:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to get bulk analysis status',
      repository_id: req.params.id
    });
  }
});

// Get available commits for bulk analysis
router.get('/repository/:id/commits', async (req, res) => {
  try {
    const { id: repositoryId } = req.params;
    const { 
      limit = 100,
      offset = 0,
      has_diff_content = 'all' // 'all', 'true', 'false'
    } = req.query;

    console.log(`📋 Getting available commits for repository ${repositoryId}`);

    // Validate repository exists
    const repoQuery = 'SELECT id, repository_name FROM all_repositories WHERE id = $1';
    const repoResult = await database.query(repoQuery, [repositoryId]);
    
    if (repoResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: 'Repository not found',
        repository_id: repositoryId
      });
    }

    // Build query based on has_diff_content filter
    let whereClause = 'WHERE rcd.repository_id = $1';
    let queryParams = [repositoryId];
    let paramIndex = 2;

    if (has_diff_content === 'true') {
      whereClause += ` AND EXISTS (
        SELECT 1 FROM diff_contents dc 
        WHERE dc.commit_id = rcd.id
      )`;
    } else if (has_diff_content === 'false') {
      whereClause += ` AND NOT EXISTS (
        SELECT 1 FROM diff_contents dc 
        WHERE dc.commit_id = rcd.id
      )`;
    }

    const query = `
      SELECT 
        rcd.id,
        rcd.commit_sha,
        rcd.message,
        rcd.committed_at,
        CASE 
          WHEN EXISTS (SELECT 1 FROM diff_contents dc WHERE dc.commit_id = rcd.id) 
          THEN true 
          ELSE false 
        END as has_diff_content,
        (
          SELECT COUNT(*) 
          FROM repository_commit_files rcf 
          WHERE rcf.commit_id = rcd.id
        ) as files_count
      FROM repository_commit_details rcd
      ${whereClause}
      ORDER BY rcd.committed_at DESC
      LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
    `;

    queryParams.push(parseInt(limit), parseInt(offset));

    const result = await database.query(query, queryParams);

    // Get total count for pagination
    const countQuery = `
      SELECT COUNT(*) as total
      FROM repository_commit_details rcd
      ${whereClause}
    `;
    
    const countResult = await database.query(countQuery, [repositoryId]);
    const totalCount = parseInt(countResult.rows[0].total);

    res.json({
      success: true,
      repository_id: repositoryId,
      commits: result.rows,
      pagination: {
        total: totalCount,
        limit: parseInt(limit),
        offset: parseInt(offset),
        has_more: (parseInt(offset) + parseInt(limit)) < totalCount
      }
    });

  } catch (error) {
    console.error('Error in get commits endpoint:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to get commits',
      repository_id: req.params.id
    });
  }
});

module.exports = router;
