import { NextApiRequest, NextApiResponse } from 'next'

/**
 * AI Learning Insights API
 * 
 * Provides access to the stop loss decision learning system insights
 */

interface LearningResult {
  success: boolean;
  message: string;
  data?: any;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { method } = req

  try {
    switch (method) {
      case 'GET':
        return await getLearningInsights(req, res)
      case 'POST':
        return await manageLearningSystem(req, res)
      default:
        res.setHeader('Allow', ['GET', 'POST'])
        return res.status(405).json({ success: false, error: `Method ${method} not allowed` })
    }
  } catch (error: any) {
    console.error('Learning insights API error:', error)
    return res.status(500).json({
      success: false,
      error: 'Internal server error',
      message: error?.message || 'Unknown error'
    })
  }
}

async function getLearningInsights(req: NextApiRequest, res: NextApiResponse) {
  try {
    // Import the learning system dynamically
    const EnhancedAutonomousRiskManager = require('../../../lib/enhanced-autonomous-risk-manager.js')
    const riskManager = new EnhancedAutonomousRiskManager()
    
    // Get comprehensive learning status
    const learningStatus = await riskManager.getLearningStatus()
    
    // Get decision patterns
    const StopLossDecisionLearner = require('../../../lib/stop-loss-decision-learner.js')
    const learner = new StopLossDecisionLearner()
    const patterns = await learner.analyzeDecisionPatterns()
    const learningReport = await learner.generateLearningReport()

    const insights = {
      success: true,
      timestamp: new Date().toISOString(),
      learningSystem: {
        status: learningStatus.isLearning ? 'ACTIVE' : 'INACTIVE',
        confidence: (learningStatus.systemConfidence * 100).toFixed(1) + '%',
        totalDecisions: learningStatus.totalDecisions,
        pendingAssessments: learningStatus.pendingAssessments,
        currentThresholds: learningStatus.currentThresholds,
        lastAnalysis: learningStatus.lastAnalysis
      },
      decisionPatterns: {
        successful: patterns?.successfulPatterns || [],
        failures: patterns?.failurePatterns || [],
        optimalTiming: patterns?.optimalTiming || {},
        distanceOptimization: patterns?.distanceOptimization || {}
      },
      performanceMetrics: {
        overallSuccessRate: calculateOverallSuccessRate(patterns),
        mostSuccessfulDecision: findMostSuccessfulDecision(patterns),
        improvementTrend: calculateImprovementTrend(learningReport),
        confidenceLevel: learningStatus.systemConfidence
      },
      recommendations: learningReport?.recommendations || [],
      systemHealth: {
        learningActive: learningStatus.isLearning,
        dataQuality: assessDataQuality(patterns),
        systemMaturity: assessSystemMaturity(learningStatus.totalDecisions),
        readyForAutonomy: learningStatus.systemConfidence > 0.7
      }
    }

    return res.status(200).json(insights)
  } catch (error: any) {
    console.error('Error getting learning insights:', error)
    return res.status(500).json({
      success: false,
      error: 'Failed to retrieve learning insights',
      message: error?.message || 'Unknown error'
    })
  }
}

async function manageLearningSystem(req: NextApiRequest, res: NextApiResponse) {
  try {
    const { action, parameters } = req.body

    const EnhancedAutonomousRiskManager = require('../../../lib/enhanced-autonomous-risk-manager.js')
    const riskManager = new EnhancedAutonomousRiskManager()

    let result: LearningResult = { success: false, message: 'Unknown action' }

    switch (action) {
      case 'updateThresholds':
        // Update learning thresholds
        if (parameters?.thresholds) {
          await riskManager.updateThresholdsFromLearning()
          result = { success: true, message: 'Thresholds updated from learning data' }
        }
        break

      case 'generateReport':
        // Force generate a new learning report
        const StopLossDecisionLearner = require('../../../lib/stop-loss-decision-learner.js')
        const learner = new StopLossDecisionLearner()
        const report = await learner.generateLearningReport()
        result = { success: true, message: 'Report generated', data: report }
        break

      case 'getRecommendation':
        // Get smart recommendation for current situation
        if (parameters?.situation) {
          const recommendation = await riskManager.learner.getSmartRecommendation(parameters.situation)
          result = { success: true, message: 'Recommendation generated', data: recommendation }
        }
        break

      case 'assessPendingDecisions':
        // Force assessment of pending decisions
        await riskManager.assessDecisionOutcomes()
        result = { success: true, message: 'Pending decisions assessed' }
        break

      default:
        result = { success: false, message: `Unknown action: ${action}` }
    }

    return res.status(200).json(result)
  } catch (error: any) {
    console.error('Error managing learning system:', error)
    return res.status(500).json({
      success: false,
      error: 'Failed to manage learning system',
      message: error?.message || 'Unknown error'
    })
  }
}

// Helper functions
function calculateOverallSuccessRate(patterns: any): number {
  if (!patterns?.successfulPatterns || patterns.successfulPatterns.length === 0) return 0
  
  const totalSamples = patterns.successfulPatterns.reduce((sum: number, p: any) => sum + p.sampleSize, 0)
  const totalSuccesses = patterns.successfulPatterns.reduce((sum: number, p: any) => sum + (p.sampleSize * p.successRate / 100), 0)
  
  return totalSamples > 0 ? parseFloat((totalSuccesses / totalSamples * 100).toFixed(1)) : 0
}

function findMostSuccessfulDecision(patterns: any): any {
  if (!patterns?.successfulPatterns || patterns.successfulPatterns.length === 0) {
    return { type: 'NONE', rate: 0 }
  }
  
  const best = patterns.successfulPatterns.reduce((best: any, current: any) => 
    current.successRate > best.successRate ? current : best
  )
  
  return {
    type: best.decisionType,
    rate: best.successRate.toFixed(1) + '%',
    samples: best.sampleSize
  }
}

function calculateImprovementTrend(report: any): string {
  // Simple trend calculation - in production, this would analyze historical data
  if (!report?.summary?.systemConfidence) return 'INSUFFICIENT_DATA'
  
  const confidence = report.summary.systemConfidence
  if (confidence > 0.8) return 'EXCELLENT'
  if (confidence > 0.6) return 'IMPROVING'
  if (confidence > 0.4) return 'LEARNING'
  return 'INITIALIZING'
}

function assessDataQuality(patterns: any): string {
  const totalDecisions = patterns?.successfulPatterns?.reduce((sum: number, p: any) => sum + p.sampleSize, 0) || 0
  
  if (totalDecisions >= 50) return 'HIGH'
  if (totalDecisions >= 20) return 'MEDIUM'
  if (totalDecisions >= 5) return 'LOW'
  return 'INSUFFICIENT'
}

function assessSystemMaturity(totalDecisions: number): string {
  if (totalDecisions >= 100) return 'EXPERT'
  if (totalDecisions >= 50) return 'INTERMEDIATE'
  if (totalDecisions >= 20) return 'NOVICE'
  if (totalDecisions >= 5) return 'BEGINNER'
  return 'LEARNING'
}
