// DBIS Global Multiversal Monetary Theory - Stability Service
// Dimensional consistency enforcement

import prisma from '@/shared/database/prisma';
import { gmmtUnitsService } from './gmmt-units.service';


export class GmmtStabilityService {
  /**
   * Verify dimensional consistency
   * Monetary structures must remain coherent across all realities
   */
  async verifyDimensionalConsistency(layerId: string): Promise<boolean> {
    const layer = await prisma.reality_layers.findUnique({
      where: { layerId },
      include: {
        monetaryUnits: true,
      },
    });

    if (!layer) {
      return false;
    }

    // Check coherence level
    if (layer.coherenceLevel < 0.8) {
      return false;
    }

    // Verify all units have anchor values or derivation formulas
    for (const unit of layer.monetaryUnits) {
      if (!unit.anchorValue && !unit.derivationFormula) {
        return false;
      }
    }

    return true;
  }

  /**
   * Check consistency across all layers
   */
  async checkCrossLayerConsistency(): Promise<{
    consistent: boolean;
    inconsistencies: Array<{ layerId: string; issue: string }>;
  }> {
    const layers = await gmmtUnitsService.getRealityLayers();
    const inconsistencies: Array<{ layerId: string; issue: string }> = [];

    for (const layer of layers) {
      const isConsistent = await this.verifyDimensionalConsistency(layer.layerId);
      if (!isConsistent) {
        inconsistencies.push({
          layerId: layer.layerId,
          issue: `Dimensional consistency check failed for layer ${layer.layerName}`,
        });
      }

      // Check coherence level
      if (layer.coherenceLevel < 0.8) {
        inconsistencies.push({
          layerId: layer.layerId,
          issue: `Low coherence level: ${layer.coherenceLevel}`,
        });
      }
    }

    return {
      consistent: inconsistencies.length === 0,
      inconsistencies,
    };
  }

  /**
   * Update layer coherence level
   */
  async updateCoherenceLevel(layerId: string, coherenceLevel: number) {
    if (coherenceLevel < 0 || coherenceLevel > 1) {
      throw new Error('Coherence level must be between 0 and 1');
    }

    return await prisma.reality_layers.update({
      where: { layerId },
      data: { coherenceLevel },
    });
  }

  /**
   * Get stability report
   */
  async getStabilityReport() {
    const layers = await gmmtUnitsService.getRealityLayers();
    const consistencyCheck = await this.checkCrossLayerConsistency();

    return {
      totalLayers: layers.length,
      authenticatedLayers: layers.filter((l) => l.authenticationStatus === 'authenticated').length,
      averageCoherence: layers.reduce((sum, l) => sum + l.coherenceLevel.toNumber(), 0) / layers.length,
      consistencyCheck,
      layers: layers.map((layer) => ({
        layerId: layer.layerId,
        layerName: layer.layerName,
        layerType: layer.layerType,
        coherenceLevel: layer.coherenceLevel.toNumber(),
        authenticationStatus: layer.authenticationStatus,
        unitCount: layer.monetaryUnits.length,
      })),
    };
  }
}

export const gmmtStabilityService = new GmmtStabilityService();

