// DBIS Prime-Reality Oversight Engine - Alignment Service
// Enforces Prime Reality alignment

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { Decimal } from '@prisma/client/runtime/library';
import { proeOversightService } from './proe-oversight.service';


export interface AlignmentResult {
  alignmentId: string;
  deviationId: string;
  adjustmentAmount: Decimal;
  aligned: boolean;
}

export class ProeAlignmentService {
  /**
   * Enforce Prime Reality alignment
   * if deviation > threshold: enforce_prime_reality_alignment()
   */
  async enforcePrimeRealityAlignment(deviationId: string): Promise<AlignmentResult> {
    const alignmentId = `PROE-ALIGN-${uuidv4()}`;

    const deviation = await prisma.primeRealityDeviation.findUnique({
      where: { deviationId },
    });

    if (!deviation) {
      throw new Error(`Deviation not found: ${deviationId}`);
    }

    // Calculate adjustment to align with Prime Reality
    const adjustmentAmount = deviation.primeRealityState.minus(deviation.alternateRealityState);

    // Create alignment enforcement
    const alignment = await prisma.alignmentEnforcement.create({
      data: {
        alignmentId,
        deviationId,
        adjustmentAmount: adjustmentAmount.abs(),
        aligned: true,
        status: 'enforced',
      },
    });

    // Update reality state to align with Prime Reality
    await prisma.realityState.updateMany({
      where: {
        realityId: deviation.realityId,
        realityType: deviation.realityType,
      },
      data: {
        stateData: {
          value: deviation.primeRealityState.toNumber(),
          aligned: true,
        },
        updatedAt: new Date(),
      },
    });

    // Update deviation status
    await prisma.primeRealityDeviation.update({
      where: { deviationId },
      data: {
        requiresAlignment: false,
        status: 'aligned',
        updatedAt: new Date(),
      },
    });

    return {
      alignmentId,
      deviationId,
      adjustmentAmount: adjustmentAmount.abs(),
      aligned: true,
    };
  }

  /**
   * Get alignment by ID
   */
  async getAlignment(alignmentId: string) {
    return await prisma.alignmentEnforcement.findUnique({
      where: { alignmentId },
      include: {
        deviation: true,
      },
    });
  }

  /**
   * Get all alignments
   */
  async getAllAlignments() {
    return await prisma.alignmentEnforcement.findMany({
      where: { status: 'enforced' },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Enforce alignment for all deviations requiring alignment
   */
  async enforceAllAlignments() {
    const deviations = await proeOversightService.getActiveDeviations();

    const results: AlignmentResult[] = [];

    for (const deviation of deviations) {
      const result = await this.enforcePrimeRealityAlignment(deviation.deviationId);
      results.push(result);
    }

    return results;
  }
}

export const proeAlignmentService = new ProeAlignmentService();

