/**
 * API Route: TransportTrackerAgent Management
 * GET /api/agents/transport-tracker - Get agent status and metrics
 * POST /api/agents/transport-tracker - Control agent (start/stop/run)
 */

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

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

  if (req.method === 'GET') {
    try {
      const metrics = agent.getMetrics();
      const alerts = agent.getAlerts();
      const networkStats = agent.getNetworkStats();
      const patterns = agent.getPatterns();

      res.status(200).json({
        success: true,
        data: {
          agent: {
            id: agent.config.id,
            name: agent.config.name,
            description: agent.config.description,
            status: agent.status,
            priority: agent.config.priority,
            intervalMs: agent.config.intervalMs,
            enabled: agent.config.enabled
          },
          metrics,
          alerts: alerts.filter(a => !a.acknowledged).slice(-10),
          summary: {
            networkStats: networkStats ? {
              totalEvents: networkStats.totalEvents,
              totalDistanceKm: networkStats.totalDistanceKm,
              totalCarbonKg: networkStats.totalCarbonKg,
              greenTransportPercentage: networkStats.greenTransportPercentage
            } : null,
            patternsDetected: patterns.length,
            highSeverityPatterns: patterns.filter(p => p.severity === 'high').length
          }
        }
      });
    } catch (error: any) {
      console.error('Error getting transport tracker agent 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 || typeof action !== 'string') {
        return res.status(400).json({
          success: false,
          error: 'Action is required (start, stop, run)'
        });
      }

      let result: any = {};

      switch (action) {
        case 'start':
          await agent.start();
          result = { message: 'Agent started', status: agent.status };
          break;

        case 'stop':
          await agent.stop();
          result = { message: 'Agent stopped', status: agent.status };
          break;

        case 'run':
          // Run a single execution cycle
          const taskResult = await agent.runOnce();
          result = {
            message: 'Agent cycle completed',
            status: agent.status,
            taskResult
          };
          break;

        case 'pause':
          agent.pause();
          result = { message: 'Agent paused', status: agent.status };
          break;

        case 'resume':
          agent.resume();
          result = { message: 'Agent resumed', status: agent.status };
          break;

        default:
          return res.status(400).json({
            success: false,
            error: `Unknown action: ${action}. Valid actions: start, stop, run, pause, resume`
          });
      }

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