// DBIS Meta-Reality Economic Convergence Protocol - Harmonization Service
// Stabilizes harmonized field

import { v4 as uuidv4 } from 'uuid';
import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { mrecpConvergenceService } from './mrecp-convergence.service';


export interface HarmonizationResult {
  harmonizationId: string;
  convergenceId: string;
  adjustmentAmount: Decimal;
  harmonized: boolean;
}

export class MrecpHarmonizationService {
  /**
   * Apply harmonization to stabilize field
   */
  async applyHarmonization(convergenceId: string): Promise<HarmonizationResult> {
    const convergence = await prisma.realityConvergence.findUnique({
      where: { convergenceId },
      include: {
        divergences: {
          where: { status: 'active' },
        },
      },
    });

    if (!convergence) {
      throw new Error(`Convergence not found: ${convergenceId}`);
    }

    // Calculate total adjustment needed
    let totalAdjustment = new Decimal(0);
    for (const divergence of convergence.divergences) {
      totalAdjustment = totalAdjustment.plus(divergence.divergenceAmount);
    }

    // Create harmonization
    const harmonizationId = `MRECP-HARM-${uuidv4()}`;
    const harmonization = await prisma.economicHarmonization.create({
      data: {
        harmonizationId,
        convergenceId,
        adjustmentAmount: totalAdjustment,
        status: 'applied',
      },
    });

    // Update convergence stability
    const harmonized = convergence.stable || totalAdjustment.abs().lessThan(new Decimal(0.01));

    if (harmonized) {
      await prisma.realityConvergence.update({
        where: { convergenceId },
        data: {
          stable: true,
          updatedAt: new Date(),
        },
      });
    }

    return {
      harmonizationId,
      convergenceId,
      adjustmentAmount: totalAdjustment,
      harmonized,
    };
  }

  /**
   * Get harmonization by ID
   */
  async getHarmonization(harmonizationId: string) {
    return await prisma.economicHarmonization.findUnique({
      where: { harmonizationId },
      include: {
        convergence: true,
      },
    });
  }

  /**
   * Get all harmonizations for convergence
   */
  async getHarmonizationsForConvergence(convergenceId: string) {
    return await prisma.economicHarmonization.findMany({
      where: { convergenceId },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Apply harmonization to all unstable convergences
   */
  async harmonizeAllUnstable() {
    const convergences = await mrecpConvergenceService.getAllConvergences();
    const unstable = convergences.filter((c) => !c.stable);

    const results: HarmonizationResult[] = [];

    for (const convergence of unstable) {
      const result = await this.applyHarmonization(convergence.convergenceId);
      results.push(result);
    }

    return results;
  }
}

export const mrecpHarmonizationService = new MrecpHarmonizationService();

