/**
 * API Route: Get lineage analysis for a specific plant
 * GET /api/agents/lineage/[plantId]
 */

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

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 { plantId } = req.query;

    if (!plantId || typeof plantId !== 'string') {
      return res.status(400).json({ success: false, error: 'Invalid plant ID' });
    }

    // Check if plant exists in blockchain
    const blockchain = getBlockchain();
    const plant = blockchain.findPlant(plantId);

    if (!plant) {
      return res.status(404).json({ success: false, error: 'Plant not found' });
    }

    const agent = getPlantLineageAgent();

    // Get cached lineage analysis from agent
    let analysis = agent.getLineageAnalysis(plantId);

    // If not cached, the agent hasn't scanned this plant yet
    // Return basic info with a note that full analysis is pending
    if (!analysis) {
      return res.status(200).json({
        success: true,
        plantId,
        cached: false,
        message: 'Lineage analysis pending. Agent will analyze on next scan cycle.',
        plant: {
          id: plant.id,
          species: plant.species,
          generation: plant.generation,
          status: plant.status,
          parentPlantId: plant.parentPlantId,
          childPlants: plant.childPlants || [],
        },
      });
    }

    res.status(200).json({
      success: true,
      plantId,
      cached: true,
      analysis: {
        generation: analysis.generation,
        ancestors: analysis.ancestors,
        descendants: analysis.descendants,
        totalLineageSize: analysis.totalLineageSize,
        propagationChain: analysis.propagationChain,
        geographicSpread: analysis.geographicSpread,
        oldestAncestorDate: analysis.oldestAncestorDate,
        healthScore: analysis.healthScore,
      },
      plant: {
        id: plant.id,
        species: plant.species,
        generation: plant.generation,
        status: plant.status,
        propagationType: plant.propagationType,
        location: plant.location,
        dateAcquired: plant.dateAcquired,
      },
    });
  } catch (error: any) {
    console.error('Error getting lineage analysis:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
