// DBIS Unified Holographic Economic Model - Analytics Service
// Predictive analytics across simulations

import prisma from '@/shared/database/prisma';
import { uhemEncodingService } from './uhem-encoding.service';
import { uhemProjectionService } from './uhem-projection.service';


export class UhemAnalyticsService {
  /**
   * Analyze economic trends across realities
   */
  async analyzeTrends(timeRange?: { start: Date; end: Date }) {
    const states = timeRange
      ? await uhemEncodingService.getStatesByTimeRange(timeRange.start, timeRange.end)
      : [await uhemEncodingService.getLatestState()].filter(Boolean);

    if (states.length === 0) {
      return {
        statesAnalyzed: 0,
        trends: [],
      };
    }

    // Analyze trends
    const trends = {
      cbdcFlowTrend: this.analyzeCbdcFlow(states),
      fxMatrixTrend: this.analyzeFxMatrix(states),
      ssuPressureTrend: this.analyzeSsuPressure(states),
      stabilityTrend: this.analyzeStability(states),
    };

    return {
      statesAnalyzed: states.length,
      timeRange: timeRange || {
        start: states[states.length - 1].timestamp,
        end: states[0].timestamp,
      },
      trends,
    };
  }

  /**
   * Analyze CBDC flow trends
   */
  private analyzeCbdcFlow(states: any[]) {
    // In production, this would perform complex analysis
    return {
      averageFlow: 0,
      trend: 'stable',
      volatility: 0,
    };
  }

  /**
   * Analyze FX matrix trends
   */
  private analyzeFxMatrix(states: any[]) {
    // In production, this would perform complex analysis
    return {
      averageVolatility: 0,
      trend: 'stable',
      correlations: {},
    };
  }

  /**
   * Analyze SSU pressure trends
   */
  private analyzeSsuPressure(states: any[]) {
    // In production, this would perform complex analysis
    return {
      averagePressure: 0,
      trend: 'stable',
      peaks: [],
    };
  }

  /**
   * Analyze stability trends
   */
  private analyzeStability(states: any[]) {
    // In production, this would perform complex analysis
    return {
      averageStability: 0,
      trend: 'stable',
      riskFactors: [],
    };
  }

  /**
   * Get projection accuracy statistics
   */
  async getProjectionAccuracy() {
    const projections = await prisma.economicProjection.findMany({
      where: {
        status: 'validated',
        accuracy: { not: null },
      },
      orderBy: { projectedAt: 'desc' },
      take: 100,
    });

    if (projections.length === 0) {
      return {
        totalProjections: 0,
        averageAccuracy: 0,
        accuracyDistribution: {},
      };
    }

    const accuracies = projections
      .map((p) => p.accuracy?.toNumber() || 0)
      .filter((a) => a > 0);

    const averageAccuracy = accuracies.reduce((sum, a) => sum + a, 0) / accuracies.length;

    return {
      totalProjections: projections.length,
      averageAccuracy,
      minAccuracy: Math.min(...accuracies),
      maxAccuracy: Math.max(...accuracies),
      accuracyDistribution: {
        high: accuracies.filter((a) => a >= 0.9).length,
        medium: accuracies.filter((a) => a >= 0.7 && a < 0.9).length,
        low: accuracies.filter((a) => a < 0.7).length,
      },
    };
  }

  /**
   * Get cross-reality comparison
   */
  async getCrossRealityComparison() {
    const projections = await prisma.economicProjection.findMany({
      where: { status: 'active' },
      distinct: ['targetReality'],
    });

    const comparisons = await Promise.all(
      projections.map(async (p) => {
        const stateProjections = await uhemProjectionService.getProjectionsForState(p.stateId);
        return {
          reality: p.targetReality,
          projectionCount: stateProjections.length,
          latestProjection: stateProjections[0]?.projectedAt,
        };
      })
    );

    return {
      realities: comparisons,
      totalRealities: comparisons.length,
    };
  }
}

export const uhemAnalyticsService = new UhemAnalyticsService();

