// API route to get detailed learning system status and visibility
import { NextResponse } from 'next/server';

// Import the automation instance to get learning status
async function getAutomationInstance() {
  try {
    // Import the singleton automation instance
    const { getAutomationInstance } = await import('../../../../lib/automation-singleton.js');
    return getAutomationInstance();
  } catch (error) {
    console.error('❌ Could not get automation instance:', error);
    return null;
  }
}

export async function GET() {
  try {
    const automation = await getAutomationInstance();
    
    if (!automation) {
      return NextResponse.json({
        success: false,
        message: 'Automation instance not available'
      }, { status: 503 });
    }

    // Check if automation has learning capabilities
    if (typeof automation.getLearningStatus !== 'function') {
      return NextResponse.json({
        success: true,
        learningSystem: {
          enabled: false,
          message: 'Basic automation running - learning system not integrated',
          recommendation: 'Restart automation to enable AI learning system'
        }
      });
    }

    // Get detailed learning status
    const learningStatus = await automation.getLearningStatus();
    const automationStatus = automation.getStatus();

    return NextResponse.json({
      success: true,
      learningSystem: {
        ...learningStatus,
        automationRunning: automationStatus.isActive || automationStatus.isRunning,
        totalCycles: automationStatus.totalCycles || automationStatus.stats?.totalCycles || 0,
        totalTrades: automationStatus.totalTrades || automationStatus.stats?.totalTrades || 0
      },
      visibility: {
        decisionTrackingActive: learningStatus.activeDecisions > 0,
        learningDatabaseConnected: learningStatus.enabled,
        aiEnhancementsActive: learningStatus.learningActive,
        lastUpdateTime: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('❌ Error getting learning system status:', error);
    
    return NextResponse.json({
      success: false,
      error: error.message,
      learningSystem: {
        enabled: false,
        error: 'Failed to retrieve learning status'
      }
    }, { status: 500 });
  }
}
