// Neural Consensus Engine (NCE) Service
// Main neural consensus engine
// consensus_state = neural_vote(SCB_signals + AI_forecasts + quantum_signatures)

import { Prisma } from '@prisma/client';
import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { nceNeuralService } from './nce-neural.service';
import { nceQuantumService } from './nce-quantum.service';
import { nceStateService } from './nce-state.service';


export interface CreateConsensusRequest {
  ledgerStateHash: string;
  scbSignals: Record<string, unknown>;
  aiForecasts: Record<string, unknown>;
  confidenceThreshold?: number; // Default 97%
}

export class NceEngineService {
  /**
   * Create consensus state
   * Formula: consensus_state = neural_vote(SCB_signals + AI_forecasts + quantum_signatures)
   */
  async createConsensus(request: CreateConsensusRequest) {
    const stateId = `NCE-STATE-${uuidv4()}`;
    const confidenceThreshold = request.confidenceThreshold || 97;

    // Process neural vote
    const neuralVote = await nceNeuralService.processNeuralVote({
      scbSignals: request.scbSignals as unknown as Record<string, unknown>,
      aiForecasts: request.aiForecasts as unknown as Record<string, unknown>,
    });

    // Get quantum signatures
    const quantumSignatures = await nceQuantumService.getQuantumSignatures(request.ledgerStateHash);

    // Create consensus state
    const consensusState = await prisma.neural_consensus_states.create({
      data: {
        id: uuidv4(),
        stateId,
        ledgerStateHash: request.ledgerStateHash,
        neuralVote: new Decimal(neuralVote.confidence),
        scbSignals: request.scbSignals as Prisma.InputJsonValue,
        aiForecasts: request.aiForecasts as Prisma.InputJsonValue,
        quantumSignatures: quantumSignatures as Prisma.InputJsonValue,
        consensusResult: neuralVote.confidence >= confidenceThreshold ? 'approved' : 'pending',
        confidenceThreshold: new Decimal(confidenceThreshold),
        status: 'pending',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    // Process layers
      await nceNeuralService.createLayers(stateId, {
        scbSignals: request.scbSignals,
        aiForecasts: request.aiForecasts,
      });

    // Validate quantum signatures
    const quantumValid = await nceQuantumService.validateSignatures(stateId, quantumSignatures);

    // Final consensus check
    if (neuralVote.confidence >= confidenceThreshold && quantumValid) {
      await this.confirmConsensus(stateId);
    }

    return consensusState;
  }

  /**
   * Confirm consensus
   */
  async confirmConsensus(stateId: string) {
    const state = await prisma.neural_consensus_states.findUnique({
      where: { stateId },
    });

    if (!state) {
      throw new Error(`Consensus state not found: ${stateId}`);
    }

    // Validate state integrity
    const integrityValid = await nceStateService.validateStateIntegrity(state.ledgerStateHash);

    if (!integrityValid) {
      throw new Error('State integrity validation failed');
    }

    return prisma.neural_consensus_states.update({
      where: { stateId },
      data: {
        status: 'confirmed',
        consensusResult: 'approved',
        confirmedAt: new Date(),
      },
    });
  }

  /**
   * Get consensus state
   */
  async getConsensusState(stateId: string) {
    const state = await prisma.neural_consensus_states.findUnique({
      where: { stateId },
      include: {
        neural_layers: true,
        neural_quantum_signatures: true,
      },
    });

    if (!state) {
      throw new Error(`Consensus state not found: ${stateId}`);
    }

    return state;
  }

  /**
   * Get consensus states
   */
  async getConsensusStates(filters?: {
    status?: string;
    consensusResult?: string;
  }) {
    const where: Record<string, unknown> = {};

    if (filters?.status) {
      where.status = filters.status;
    }
    if (filters?.consensusResult) {
      where.consensusResult = filters.consensusResult;
    }

    return prisma.neural_consensus_states.findMany({
      where,
      include: {
        _count: {
          select: {
            neural_layers: true,
            neural_quantum_signatures: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });
  }
}

export const nceEngineService = new NceEngineService();

