/**
 * API Route: Analyze growth correlations across all plants
 * GET /api/environment/analysis?species=tomato (optional species filter)
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getBlockchain } from '../../../lib/blockchain/manager';
import { analyzeGrowthCorrelation } from '../../../lib/environment/analysis';

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

  try {
    const { species } = req.query;

    const blockchain = getBlockchain();

    // Get all plants
    let allPlants = Array.from(
      new Set(blockchain.chain.map(block => block.plant.id))
    )
      .map(id => blockchain.getPlant(id)!)
      .filter(Boolean);

    // Filter by species if specified
    if (species && typeof species === 'string') {
      allPlants = allPlants.filter(
        p =>
          p.scientificName?.toLowerCase().includes(species.toLowerCase()) ||
          p.commonName?.toLowerCase().includes(species.toLowerCase())
      );
    }

    // Only include plants with environmental data
    const plantsWithEnv = allPlants.filter(p => p.environment);

    if (plantsWithEnv.length === 0) {
      return res.status(200).json({
        success: true,
        message: 'No plants with environmental data found',
        plantsAnalyzed: 0,
      });
    }

    const analysis = analyzeGrowthCorrelation(plantsWithEnv);

    // Calculate some additional statistics
    const successRate =
      (plantsWithEnv.filter(
        p => p.status === 'mature' || p.status === 'flowering' || p.status === 'fruiting'
      ).length /
        plantsWithEnv.length) *
      100;

    const locationTypes = plantsWithEnv.reduce((acc, p) => {
      const type = p.environment!.location.type;
      acc[type] = (acc[type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const soilTypes = plantsWithEnv.reduce((acc, p) => {
      const type = p.environment!.soil.type;
      acc[type] = (acc[type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    res.status(200).json({
      success: true,
      plantsAnalyzed: plantsWithEnv.length,
      successRate: Math.round(successRate),
      insights: analysis.insights,
      statistics: {
        locationTypes,
        soilTypes,
        avgTemperature:
          plantsWithEnv.reduce((sum, p) => sum + (p.environment!.climate.temperatureDay || 0), 0) /
          plantsWithEnv.length,
        avgHumidity:
          plantsWithEnv.reduce((sum, p) => sum + (p.environment!.climate.humidityAverage || 0), 0) /
          plantsWithEnv.length,
        avgSoilPH:
          plantsWithEnv.reduce((sum, p) => sum + (p.environment!.soil.pH || 0), 0) /
          plantsWithEnv.length,
      },
    });
  } catch (error: any) {
    console.error('Error analyzing growth correlation:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
