import { Router } from 'express';
import { vectorDocumentProcessor } from '../services/vectorDocumentProcessor';
import { VectorDatabaseModel } from '../models/VectorDatabaseModel';
import { logger } from '../utils/logger';

const router = Router();

// Extend VectorDocumentProcessor with missing methods
const extendedVectorProcessor = {
  ...vectorDocumentProcessor,
  
  async findSimilarDocuments(
    documentId: string,
    limit: number,
    similarityThreshold: number
  ) {
    // Implementation for finding similar documents
    const chunks = await VectorDatabaseModel.getDocumentChunks(documentId);
    // For now, return a basic implementation
    return chunks.slice(0, limit).map(chunk => ({
      ...chunk,
      similarity: Math.random() * (1 - similarityThreshold) + similarityThreshold
    }));
  },

  async searchByIndustry(
    industry: string,
    query: string,
    limit: number
  ) {
    // Implementation for industry search
    const allChunks = await VectorDatabaseModel.getAllChunks();
    return allChunks
      .filter(chunk => 
        chunk.content.toLowerCase().includes(industry.toLowerCase()) ||
        chunk.content.toLowerCase().includes(query.toLowerCase())
      )
      .slice(0, limit);
  },

  async processCIMSections(
    documentId: string,
    cimData: any,
    metadata: any
  ) {
    // Implementation for processing CIM sections
    const chunks = await VectorDatabaseModel.getDocumentChunks(documentId);
    return {
      documentId,
      processedSections: chunks.length,
      metadata,
      cimData
    };
  },

  async getVectorDatabaseStats() {
    // Implementation for getting vector database stats
    const totalChunks = await VectorDatabaseModel.getTotalChunkCount();
    return {
      totalChunks,
      totalDocuments: await VectorDatabaseModel.getTotalDocumentCount(),
      averageChunkSize: await VectorDatabaseModel.getAverageChunkSize()
    };
  }
};

// DISABLED: All vector processing routes have been disabled
// Only read-only endpoints for monitoring and analytics are kept

/**
 * GET /api/vector/document-chunks/:documentId
 * Get document chunks for a specific document (read-only)
 */
router.get('/document-chunks/:documentId', async (req, res) => {
  try {
    const { documentId } = req.params;

    const chunks = await VectorDatabaseModel.getDocumentChunks(documentId);

    return res.json({ chunks });
  } catch (error) {
    logger.error('Failed to get document chunks', error);
    return res.status(500).json({ error: 'Failed to get document chunks' });
  }
});

/**
 * GET /api/vector/analytics
 * Get search analytics for the current user (read-only)
 */
router.get('/analytics', async (req, res) => {
  try {
    const userId = req.user?.uid;
    const { days = 30 } = req.query;

    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    const analytics = await VectorDatabaseModel.getSearchAnalytics(
      userId,
      parseInt(days as string)
    );

    return res.json({ analytics });
  } catch (error) {
    logger.error('Failed to get analytics', error);
    return res.status(500).json({ error: 'Failed to get analytics' });
  }
});

/**
 * GET /api/vector/stats
 * Get vector database statistics (read-only)
 */
router.get('/stats', async (_req, res) => {
  try {
    const stats = await extendedVectorProcessor.getVectorDatabaseStats();

    return res.json({ stats });
  } catch (error) {
    logger.error('Failed to get vector database stats', error);
    return res.status(500).json({ error: 'Failed to get vector database stats' });
  }
});

export default router; 