import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger, Optional } from '@nestjs/common';
import { Job } from 'bullmq';
import { QUEUE_AI_ANALYSIS } from '../infrastructure/queue/queue.service';
import { workerOptionsFor } from '../infrastructure/queue/queue-definitions';
import { EventBusService } from '../common/event-bus/event-bus.service';
import { BaseDomainEvent } from '../common/events/base-domain.event';
import { ActiveRecallAnalysisWorkflow } from '../modules/ai/workflows/active-recall-analysis.workflow';
import { FeynmanEvaluationWorkflow } from '../modules/ai/workflows/feynman-evaluation.workflow';
import { AiAnalysisRepository } from '../modules/ai-analysis/ai-analysis.repository';
import { FocusItemsService } from '../modules/focus-items/focus-items.service';

class AIAnalysisCompleted extends BaseDomainEvent {
  eventType = 'ai.analysis.completed';
  constructor(public readonly payload: Record<string, any>) { super(); }
}

@Processor(QUEUE_AI_ANALYSIS, workerOptionsFor(QUEUE_AI_ANALYSIS))
export class AiAnalysisWorker extends WorkerHost {
  private readonly logger = new Logger(AiAnalysisWorker.name);

  constructor(
    private readonly recallWorkflow: ActiveRecallAnalysisWorkflow,
    private readonly feynmanWorkflow: FeynmanEvaluationWorkflow,
    private readonly repository: AiAnalysisRepository,
    @Optional() private readonly eventBus?: EventBusService,
    @Optional() private readonly focusItems?: FocusItemsService,
  ) {
    super();
  }

  async process(job: Job<{
    jobId: string;
    userId: string;
    type: 'active-recall' | 'feynman-evaluation';
    questionText?: string;
    knowledgeItemContent?: string;
    userAnswer?: string;
    knowledgeItemTitle?: string;
    userExplanation?: string;
    sessionId?: string;
    answerId?: string;
  }>) {
    const { jobId, userId, type, knowledgeItemContent, sessionId, answerId } = job.data;
    this.logger.log(`Processing AI analysis job ${job.id}, dbJobId=${jobId}, type=${type}`);

    try {
      await this.repository.updateJobStatus(jobId, 'processing');

      let result: any;
      if (type === 'feynman-evaluation') {
        result = await this.feynmanWorkflow.execute({
          userId,
          knowledgeItemTitle: job.data.knowledgeItemTitle || '',
          knowledgeItemContent: knowledgeItemContent || '',
          userExplanation: job.data.userExplanation || '',
        });
      } else {
        result = await this.recallWorkflow.execute({
          userId,
          questionText: job.data.questionText || '',
          knowledgeItemContent: knowledgeItemContent || '',
          userAnswer: job.data.userAnswer || '',
        });
      }

      await this.repository.createResult(userId, jobId, result);
      await this.repository.updateJobStatus(jobId, 'completed');

      // Publish AIAnalysisCompleted event for Review Engine
      try {
        this.eventBus?.publish(new AIAnalysisCompleted({
          userId,
          jobId,
          sessionId: sessionId || null,
          answerId: answerId || null,
          type,
          score: result.score,
          analysis: result,
          timestamp: new Date().toISOString(),
        }));
      } catch {}

      // Generate FocusItems for weaknesses
      if (result.weaknesses?.length > 0) {
        for (const w of result.weaknesses) {
          try {
            await this.focusItems?.create(userId, {
              knowledgeBaseId: result.knowledgeBaseId || 'unknown',
              title: w,
              source: 'ai-analysis',
              status: 'open',
            });
          } catch {}
        }
      }

      this.logger.log(`AI analysis job ${job.id} completed, type=${type}, score=${result.score}`);
      return result;
    } catch (err: any) {
      this.logger.error(`AI analysis job ${job.id} failed: ${err.message}`);
      await this.repository.updateJobStatus(jobId, 'failed', err.message);
      throw err;
    }
  }
}
