import { prisma } from '@shieldsai/shared-db';
import { Queue, Worker, Job } from 'bullmq';
import { Redis } from 'ioredis';

// Redis connection
const redisHost = process.env.REDIS_HOST || 'localhost';
const redisPort = parseInt(process.env.REDIS_PORT || '6379', 10);

const connection = new Redis({
  host: redisHost,
  port: redisPort,
  retryStrategy: (times: number) => Math.min(times * 50, 2000),
});

// Queue configuration
const QUEUE_CONFIG = {
  voiceprintAnalysis: {
    name: 'voiceprint-analysis',
    concurrency: parseInt(process.env.VOICEPRINT_CONCURRENCY || '3', 10),
    defaultJobTimeout: parseInt(process.env.VOICEPRINT_JOB_TIMEOUT || '30000', 10),
    maxAttempts: parseInt(process.env.VOICEPRINT_MAX_ATTEMPTS || '3', 10),
  },
};

// Create queues
export const voiceprintAnalysisQueue = new Queue(
  QUEUE_CONFIG.voiceprintAnalysis.name,
  { connection }
);

// VoicePrint analysis job processor
async function processVoiceprintAnalysis(job: Job<{
  userId: string;
  audioBuffer: Buffer;
  enrollmentId?: string;
  audioUrl?: string;
}>) {
  const { userId, audioBuffer, enrollmentId, audioUrl } = job.data;

  // Import analysis service dynamically to avoid circular dependencies
  const { analysisService } = await import(
    '../../../apps/api/src/services/voiceprint'
  );

  try {
    const result = await analysisService.analyze(userId, audioBuffer, {
      enrollmentId,
      audioUrl,
    });

    return {
      analysisId: result.id,
      isSynthetic: result.isSynthetic,
      confidence: result.confidence,
    };
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Analysis failed';
    job.updateProgress(100);
    throw new Error(message);
  }
}

// Create worker
export const voiceprintAnalysisWorker = new Worker(
  QUEUE_CONFIG.voiceprintAnalysis.name,
  processVoiceprintAnalysis,
  {
    connection,
    concurrency: QUEUE_CONFIG.voiceprintAnalysis.concurrency,
    limiter: {
      max: 10,
      duration: 1000,
    },
  }
);

// Add event handlers
voiceprintAnalysisWorker.on('completed', (job, result) => {
  console.log(`Job ${job.id} completed:`, result);
});

voiceprintAnalysisWorker.on('failed', (job, err) => {
  console.error(`Job ${job.id} failed:`, err.message);
});

voiceprintAnalysisWorker.on('error', (err) => {
  console.error('Worker error:', err.message);
});

export default {
  voiceprintAnalysisQueue,
  voiceprintAnalysisWorker,
};
