// DBIS Multiverse-Consistent FX/SSU Stability Framework - Stability Service
// Cross-reality stability calculation

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { Decimal } from '@prisma/client/runtime/library';


export interface CalculateStabilityRequest {
  realityLayer: string;
  fxStability: number;
  ssuInertia: number;
  temporalSmoothing: number;
  crossRealityDivergence: number;
}

export class MultiverseStabilityService {
  /**
   * Calculate multiverse stability index
   * Formula: stability = FX_stability + SSU_inertia + temporal_smoothing - cross_reality_divergence
   */
  async calculateStability(request: CalculateStabilityRequest) {
    const indexId = `MSI-${uuidv4()}`;

    const fxStability = new Decimal(request.fxStability);
    const ssuInertia = new Decimal(request.ssuInertia);
    const temporalSmoothing = new Decimal(request.temporalSmoothing);
    const crossRealityDivergence = new Decimal(request.crossRealityDivergence);

    const totalStability = fxStability
      .plus(ssuInertia)
      .plus(temporalSmoothing)
      .minus(crossRealityDivergence);

    const index = await prisma.multiverse_stability_indices.create({
      data: {
        id: uuidv4(),
        indexId,
        realityLayer: request.realityLayer,
        fxStability: fxStability,
        ssuInertia: ssuInertia,
        temporalSmoothing: temporalSmoothing,
        crossRealityDivergence: crossRealityDivergence,
        totalStability: totalStability,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return index;
  }

  /**
   * Get stability index by ID
   */
  async getStabilityIndex(indexId: string) {
    return await prisma.multiverse_stability_indices.findUnique({
      where: { indexId },
      include: {
        stability_calculations: true,
        reality_divergences: true,
      },
    });
  }

  /**
   * Get latest stability index for reality layer
   */
  async getLatestStabilityIndex(realityLayer: string) {
    return await prisma.multiverse_stability_indices.findFirst({
      where: {
        realityLayer,
        status: 'active',
      },
      orderBy: { calculatedAt: 'desc' },
      include: {
        stability_calculations: true,
        reality_divergences: {
          where: { status: 'detected' },
        },
      },
    });
  }

  /**
   * Get all stability indices
   */
  async getAllStabilityIndices() {
    return await prisma.multiverse_stability_indices.findMany({
      where: { status: 'active' },
      orderBy: { calculatedAt: 'desc' },
      include: {
        reality_divergences: {
          where: { status: 'detected' },
        },
      },
    });
  }
}

export const multiverseStabilityService = new MultiverseStabilityService();

