// DBIS Temporal-Multiversal FX Parity Law - Monitoring Service
// Monitors parity divergence and triggers alerts

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { Decimal } from '@prisma/client/runtime/library';
import { tmfplParityService } from './tmfpl-parity.service';


export interface DivergenceAlert {
  divergenceId: string;
  parityId: string;
  currencyPair: string;
  divergenceAmount: number;
  severity: string;
}

export class TmfplMonitoringService {
  /**
   * Monitor parity divergence
   */
  async monitorParityDivergence(parityId: string): Promise<DivergenceAlert | null> {
    const parity = await prisma.temporalFxParity.findUnique({
      where: { parityId },
    });

    if (!parity) {
      return null;
    }

    const divergence = parity.divergence.abs();
    const threshold = new Decimal(0.05); // 5% threshold
    const criticalThreshold = new Decimal(0.10); // 10% critical threshold

    if (divergence.greaterThan(criticalThreshold)) {
      // Critical divergence
      const divergenceId = `TMFPL-DIV-CRIT-${uuidv4()}`;
      await prisma.parityDivergence.create({
        data: {
          divergenceId,
          parityId,
          divergenceAmount: parity.divergence,
          severity: 'critical',
          status: 'detected',
        },
      });

      return {
        divergenceId,
        parityId,
        currencyPair: parity.currencyPair,
        divergenceAmount: parity.divergence.toNumber(),
        severity: 'critical',
      };
    } else if (divergence.greaterThan(threshold)) {
      // Warning divergence
      const divergenceId = `TMFPL-DIV-WARN-${uuidv4()}`;
      await prisma.parityDivergence.create({
        data: {
          divergenceId,
          parityId,
          divergenceAmount: parity.divergence,
          severity: 'warning',
          status: 'detected',
        },
      });

      return {
        divergenceId,
        parityId,
        currencyPair: parity.currencyPair,
        divergenceAmount: parity.divergence.toNumber(),
        severity: 'warning',
      };
    }

    return null;
  }

  /**
   * Get all active divergences
   */
  async getActiveDivergences() {
    return await prisma.parityDivergence.findMany({
      where: {
        status: 'detected',
      },
      include: {
        parity: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Get divergences by severity
   */
  async getDivergencesBySeverity(severity: string) {
    return await prisma.parityDivergence.findMany({
      where: {
        severity,
        status: 'detected',
      },
      include: {
        parity: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Monitor all parities for divergence
   */
  async monitorAllParities() {
    const parities = await prisma.temporalFxParity.findMany({
      where: {
        status: 'calculated',
      },
    });

    const alerts: DivergenceAlert[] = [];

    for (const parity of parities) {
      const alert = await this.monitorParityDivergence(parity.parityId);
      if (alert) {
        alerts.push(alert);
      }
    }

    return alerts;
  }
}

export const tmfplMonitoringService = new TmfplMonitoringService();

