// DBIS Hyper-Sovereign Monetary Nexus - Consciousness Nexus (HS3)
// Links agent-based economic intent across cognitive states

import prisma from '@/shared/database/prisma';
import type { Prisma } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';


export interface ConsciousnessState {
  agentId: string;
  cognitiveState: string;
  economicIntent: string;
  alignmentScore: number;
}

export class HsmnConsciousnessService {
  /**
   * Get Consciousness Nexus (HS3)
   */
  async getConsciousnessNexus() {
    return await prisma.hsmn_nexus_layers.findFirst({
      where: {
        layerNumber: 3,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      include: {
        hsmn_reality_states: {
          where: { status: 'active' },
        },
      },
    });
  }

  /**
   * Initialize Consciousness Nexus
   */
  async initializeConsciousnessNexus() {
    const nexusId = `HSMN-HS3-${uuidv4()}`;

    const existing = await prisma.hsmn_nexus_layers.findFirst({
      where: { layerNumber: 3, status: 'active' },
    });

    if (existing) {
      return existing;
    }

    return await prisma.hsmn_nexus_layers.create({
      data: {
        id: uuidv4(),
        id: uuidv4(),
        nexusId,
        layerNumber: 3,
        layerName: 'Consciousness Nexus',
        description: 'Links agent-based economic intent across cognitive states',
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });
  }

  /**
   * Register consciousness state
   */
  async registerConsciousnessState(
    agentId: string,
    cognitiveState: string,
    economicIntent: string,
    alignmentScore: number
  ) {
    const stateId = `HSMN-CONS-${uuidv4()}`;
    const nexus = await this.getConsciousnessNexus();

    if (!nexus) {
      throw new Error('Consciousness Nexus not initialized');
    }

    return await prisma.hsmn_reality_states.create({
      data: {
        id: uuidv4(),
        stateId,
        nexusLayerId: nexus.id,
        sovereignBankId: agentId, // Using agentId as sovereignBankId for consciousness states
        realityType: 'consciousness',
        stateData: {
          cognitiveState,
          economicIntent,
          alignmentScore,
        },
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });
  }

  /**
   * Get consciousness states for agent
   */
  async getConsciousnessStates(agentId: string) {
    const nexus = await this.getConsciousnessNexus();
    if (!nexus) {
      return [];
    }

    return await prisma.hsmn_reality_states.findMany({
      where: {
        nexusLayerId: nexus.id,
        sovereignBankId: agentId,
        realityType: 'consciousness',
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });
  }

  /**
   * Calculate aggregate alignment score
   */
  async calculateAggregateAlignment(agentId: string) {
    const states = await this.getConsciousnessStates(agentId);

    if (states.length === 0) {
      return { alignmentScore: 0, stateCount: 0 };
    }

    const scores = states.map((s) => {
      const data = s.stateData as { alignmentScore?: number };
      return data.alignmentScore || 0;
    });

    const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;

    return {
      alignmentScore: avgScore,
      stateCount: states.length,
    };
  }
}

export const hsmnConsciousnessService = new HsmnConsciousnessService();

