/**
 * API Route: PlantLineageAgent Status and Network Stats
 * GET /api/agents/lineage - Get agent status and network statistics
 * POST /api/agents/lineage - Start/stop/restart the agent
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getPlantLineageAgent } from '../../../../lib/agents';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const agent = getPlantLineageAgent();

  if (req.method === 'GET') {
    try {
      const metrics = agent.getMetrics();
      const networkStats = agent.getNetworkStats();
      const anomalies = agent.getAnomalies();

      res.status(200).json({
        success: true,
        agent: {
          id: agent.config.id,
          name: agent.config.name,
          description: agent.config.description,
          status: agent.status,
          priority: agent.config.priority,
          intervalMs: agent.config.intervalMs,
        },
        metrics: {
          tasksCompleted: metrics.tasksCompleted,
          tasksFailed: metrics.tasksFailed,
          averageExecutionMs: Math.round(metrics.averageExecutionMs),
          lastRunAt: metrics.lastRunAt,
          lastSuccessAt: metrics.lastSuccessAt,
          uptime: metrics.uptime,
        },
        networkStats,
        anomalySummary: {
          total: anomalies.length,
          bySeverity: {
            high: anomalies.filter(a => a.severity === 'high').length,
            medium: anomalies.filter(a => a.severity === 'medium').length,
            low: anomalies.filter(a => a.severity === 'low').length,
          },
        },
      });
    } catch (error: any) {
      console.error('Error getting PlantLineageAgent status:', error);
      res.status(500).json({ success: false, error: error.message || 'Internal server error' });
    }
  } else if (req.method === 'POST') {
    try {
      const { action } = req.body;

      if (!action || !['start', 'stop', 'pause', 'resume'].includes(action)) {
        return res.status(400).json({
          success: false,
          error: 'Invalid action. Must be one of: start, stop, pause, resume'
        });
      }

      switch (action) {
        case 'start':
          await agent.start();
          break;
        case 'stop':
          await agent.stop();
          break;
        case 'pause':
          agent.pause();
          break;
        case 'resume':
          agent.resume();
          break;
      }

      res.status(200).json({
        success: true,
        action,
        newStatus: agent.status,
      });
    } catch (error: any) {
      console.error('Error controlling PlantLineageAgent:', error);
      res.status(500).json({ success: false, error: error.message || 'Internal server error' });
    }
  } else {
    res.status(405).json({ success: false, error: 'Method not allowed' });
  }
}
