// DBIS Conscious-Ledger Integration Model - Analytics Service
// Behavioral analytics and intent analysis

import prisma from '@/shared/database/prisma';


export interface BehavioralAnalytics {
  agentId: string;
  totalStates: number;
  averageInfluence: number;
  contractExecutionRate: number;
  behavioralPattern: string;
}

export class ClimAnalyticsService {
  /**
   * Get behavioral analytics for agent
   */
  async getBehavioralAnalytics(agentId: string): Promise<BehavioralAnalytics> {
    const states = await prisma.consciousness_states.findMany({
      where: {
        agentId,
        status: 'active',
      },
    });

    const contracts = await prisma.cognitive_contracts.findMany({
      where: {
        state: {
          agentId,
        },
        status: 'active',
      },
    });

    const totalStates = states.length;
    const averageInfluence =
      totalStates > 0
        ? states.reduce((sum, s) => sum + s.influenceLevel, 0) / totalStates
        : 0;

    const executedContracts = contracts.filter((c) => c.executionStatus === 'executed').length;
    const contractExecutionRate = contracts.length > 0 ? executedContracts / contracts.length : 0;

    // Determine behavioral pattern
    let behavioralPattern = 'neutral';
    if (averageInfluence > 0.8) {
      behavioralPattern = 'high_influence';
    } else if (averageInfluence < 0.3) {
      behavioralPattern = 'low_influence';
    }
    if (contractExecutionRate > 0.8) {
      behavioralPattern += '_high_execution';
    } else if (contractExecutionRate < 0.3) {
      behavioralPattern += '_low_execution';
    }

    return {
      agentId,
      totalStates,
      averageInfluence,
      contractExecutionRate,
      behavioralPattern,
    };
  }

  /**
   * Get aggregate analytics across all agents
   */
  async getAggregateAnalytics() {
    const allStates = await prisma.consciousness_states.findMany({
      where: { status: 'active' },
    });

    const allContracts = await prisma.cognitive_contracts.findMany({
      where: { status: 'active' },
    });

    const uniqueAgents = new Set(allStates.map((s) => s.agentId));

    const totalAgents = uniqueAgents.size;
    const totalStates = allStates.length;
    const averageInfluence =
      totalStates > 0
        ? allStates.reduce((sum, s) => sum + s.influenceLevel, 0) / totalStates
        : 0;

    const executedContracts = allContracts.filter((c) => c.executionStatus === 'executed').length;
    const contractExecutionRate =
      allContracts.length > 0 ? executedContracts / allContracts.length : 0;

    return {
      totalAgents,
      totalStates,
      averageInfluence,
      totalContracts: allContracts.length,
      contractExecutionRate,
    };
  }

  /**
   * Get behavioral field for sovereign
   */
  async getBehavioralField(sovereignBankId: string) {
    const states = await prisma.consciousness_states.findMany({
      where: {
        agentId: sovereignBankId,
        status: 'active',
      },
    });

    if (states.length === 0) {
      return null;
    }

    // Aggregate behavioral fields
    const behavioralFields = states.map((s) => s.sovereignBehaviorField);
    const aggregatedField = behavioralFields.join('|');

    return {
      sovereignBankId,
      behavioralField: aggregatedField,
      stateCount: states.length,
    };
  }
}

export const climAnalyticsService = new ClimAnalyticsService();

