import { Injectable, Logger } from '@nestjs/common';
import * as crypto from 'crypto';
import { FeatureFlagService } from '../config/feature-flag.service';
import { LearningAnalysisSnapshotBuilder } from '../ai-job/learning-analysis-snapshot-builder';
import { AiJobCreationService } from '../ai-job/ai-job-creation.service';
import { UserAiService } from './user-ai.service';
import type { CreateAnalysisJobDto } from './user-ai.dto';

const FLAG_NAME = 'LEARNING_ANALYSIS_ENGINE_MODE';

@Injectable()
export class LearningAnalysisExecutionRouter {
  private readonly logger = new Logger(LearningAnalysisExecutionRouter.name);

  constructor(
    private readonly featureFlag: FeatureFlagService,
    private readonly snapshotBuilder: LearningAnalysisSnapshotBuilder,
    private readonly creationService: AiJobCreationService,
    private readonly legacyService: UserAiService,
  ) {}

  async analyze(userId: string, dto: CreateAnalysisJobDto) {
    const useUnified = await this.shouldUseUnified(userId);

    if (!useUnified) {
      this.logger.log(`LEARNING_ANALYSIS_ENGINE_MODE=legacy for userId=${userId}`);
      return this.legacyService.createAnalysisJob(userId, dto);
    }

    this.logger.log(`LEARNING_ANALYSIS_ENGINE_MODE=unified for userId=${userId}`);

    // Idempotency: client-provided key or deterministic content hash + window
    let effectiveId: string;
    if (dto.idempotencyKey) {
      effectiveId = dto.idempotencyKey;
    } else {
      const contentKey = crypto.createHash('sha256')
        .update([dto.targetType, dto.targetId].join('|'))
        .digest('hex').substring(0, 24);
      const windowTs = Math.floor(Date.now() / (10 * 60 * 1000));
      effectiveId = `${contentKey}:w${windowTs}`;
    }

    const snapshot = await this.snapshotBuilder.build({
      userId,
      triggerType: 'manual',
      operationId: effectiveId,
    });

    const idempotencyKey = `learning-analysis:manual:${effectiveId}`;

    const job = await this.creationService.createJob({
      userId,
      jobType: 'learning_analysis',
      triggerType: 'user_api',
      targetType: dto.targetType,
      targetId: dto.targetId,
      idempotencyKey,
      retrySnapshotContent: snapshot as unknown as Record<string, unknown>,
    });

    this.logger.log(
      `Learning Analysis Unified: jobId=${job.id} userId=${userId} ` +
      `targetType=${dto.targetType} targetId=${dto.targetId}`,
    );

    return {
      jobId: job.id,
      status: 'queued',
      engineMode: 'unified' as const,
      lifecycleStatus: 'queued',
    };
  }

  private async shouldUseUnified(userId: string): Promise<boolean> {
    try { return await this.featureFlag.isEnabled(FLAG_NAME, userId); }
    catch (err: any) { this.logger.warn(`FeatureFlag query failed, falling back to legacy: ${err.message}`); return false; }
  }
}
