/**
 * API Route: TransportTrackerAgent Analytics
 * GET /api/agents/transport-tracker/analytics - Get network stats and user analytics
 * GET /api/agents/transport-tracker/analytics?userId=xxx - Get specific user analytics
 */

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

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  try {
    const agent = getTransportTrackerAgent();
    const { userId } = req.query;

    // If userId provided, return user-specific analytics
    if (userId && typeof userId === 'string') {
      const userAnalysis = agent.getUserAnalysis(userId);

      if (!userAnalysis) {
        return res.status(404).json({
          success: false,
          error: `No analytics found for user: ${userId}`
        });
      }

      return res.status(200).json({
        success: true,
        data: {
          user: userAnalysis,
          recommendations: userAnalysis.recommendations,
          efficiency: {
            rating: userAnalysis.efficiency,
            carbonPerKm: userAnalysis.carbonPerKm,
            totalCarbonKg: userAnalysis.totalCarbonKg
          }
        }
      });
    }

    // Otherwise, return network-wide analytics
    const networkStats = agent.getNetworkStats();

    if (!networkStats) {
      return res.status(200).json({
        success: true,
        data: {
          message: 'No network statistics available yet. Run the agent to collect data.',
          networkStats: null
        }
      });
    }

    res.status(200).json({
      success: true,
      data: {
        networkStats,
        insights: {
          avgCarbonPerEvent: networkStats.avgCarbonPerEvent,
          avgDistancePerEvent: networkStats.avgDistancePerEvent,
          greenTransportPercentage: networkStats.greenTransportPercentage,
          topMethods: Object.entries(networkStats.methodDistribution)
            .sort(([, a], [, b]) => (b as number) - (a as number))
            .slice(0, 5)
            .map(([method, count]) => ({ method, count }))
        },
        trends: networkStats.dailyTrends
      }
    });
  } catch (error: any) {
    console.error('Error fetching transport tracker analytics:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
