// DBIS Multiverse-Consistent FX/SSU Stability Framework - Divergence Service
// Cross-reality divergence detection

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { Decimal } from '@prisma/client/runtime/library';
import { multiverseStabilityService } from './multiverse-stability.service';


export type DivergenceType = 'fx_divergence' | 'ssu_divergence' | 'stability_divergence';

export interface DetectDivergenceRequest {
  indexId: string;
  sourceReality: string;
  targetReality: string;
  divergenceType: DivergenceType;
  divergenceMagnitude: number;
  threshold?: number;
}

export class MultiverseDivergenceService {
  /**
   * Detect divergence between realities
   */
  async detectDivergence(request: DetectDivergenceRequest) {
    const index = await multiverseStabilityService.getStabilityIndex(request.indexId);
    if (!index) {
      throw new Error(`Stability index not found: ${request.indexId}`);
    }

    const divergenceId = `DIV-${uuidv4()}`;
    const threshold = new Decimal(request.threshold || 0.1);
    const magnitude = new Decimal(request.divergenceMagnitude);

    let alertLevel: 'info' | 'warning' | 'critical' = 'info';
    if (magnitude.gt(threshold.times(2))) {
      alertLevel = 'critical';
    } else if (magnitude.gt(threshold)) {
      alertLevel = 'warning';
    }

    const divergence = await prisma.realityDivergence.create({
      data: {
        divergenceId,
        indexId: request.indexId,
        sourceReality: request.sourceReality,
        targetReality: request.targetReality,
        divergenceType: request.divergenceType,
        divergenceMagnitude: magnitude,
        threshold: threshold,
        alertLevel,
        status: 'detected',
      },
    });

    return divergence;
  }

  /**
   * Get divergences for an index
   */
  async getDivergencesForIndex(indexId: string) {
    return await prisma.realityDivergence.findMany({
      where: { indexId },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Get unresolved divergences
   */
  async getUnresolvedDivergences() {
    return await prisma.realityDivergence.findMany({
      where: {
        status: 'detected',
      },
      orderBy: [
        { alertLevel: 'desc' },
        { createdAt: 'desc' },
      ],
    });
  }

  /**
   * Resolve divergence
   */
  async resolveDivergence(divergenceId: string) {
    return await prisma.realityDivergence.update({
      where: { divergenceId },
      data: {
        status: 'resolved',
        resolvedAt: new Date(),
      },
    });
  }

  /**
   * Get divergence statistics
   */
  async getDivergenceStatistics() {
    const allDivergences = await prisma.realityDivergence.findMany({
      where: { status: 'detected' },
    });

    return {
      total: allDivergences.length,
      byType: {
        fx_divergence: allDivergences.filter((d) => d.divergenceType === 'fx_divergence').length,
        ssu_divergence: allDivergences.filter((d) => d.divergenceType === 'ssu_divergence').length,
        stability_divergence: allDivergences.filter((d) => d.divergenceType === 'stability_divergence').length,
      },
      byAlertLevel: {
        critical: allDivergences.filter((d) => d.alertLevel === 'critical').length,
        warning: allDivergences.filter((d) => d.alertLevel === 'warning').length,
        info: allDivergences.filter((d) => d.alertLevel === 'info').length,
      },
    };
  }
}

export const multiverseDivergenceService = new MultiverseDivergenceService();

