import { generateObject } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';
import crypto from 'crypto';
import { CacheUtils } from '@/lib/cache';
export const runtime = 'nodejs';
// Cache TTL: 1 week in seconds
const CACHE_TTL_SECONDS = 60 * 60 * 24 * 7 // 7 days
;
const SuggestionsSchema = z.object({
    suggestions: z.array(z.object({
        title: z.string().describe('Short action phrase (2-4 words) like "Find endpoints" or "How do I"'),
        label: z.string().describe('Completion of the title (2-5 words) like "for user management" or "authenticate?"'),
        prompt: z.string().describe('Full question the user would ask')
    })).length(4)
});
/**
 * Generate a hash key for caching based on page context
 * Uses SHA-256 hash of endpoint details or general API info
 */ function generateCacheKey(endpointIndex, currentEndpointId) {
    let content;
    if (currentEndpointId) {
        // For specific endpoint: hash the endpoint details
        const endpoint = endpointIndex.find((e)=>e.id === currentEndpointId);
        content = endpoint ? `endpoint:${endpoint.id}:${endpoint.name}:${endpoint.method}:${endpoint.path}` : `endpoint:${currentEndpointId}`;
    } else {
        // For general API: hash based on endpoint count and first few endpoint signatures
        const signature = endpointIndex.slice(0, 10).map((e)=>`${e.method}:${e.path}`).join('|');
        content = `general:${endpointIndex.length}:${signature}`;
    }
    const hash = crypto.createHash('sha256').update(content).digest('hex').slice(0, 16);
    return `suggestions:${hash}`;
}
function buildSuggestionPrompt(endpoints, currentEndpointId) {
    const currentEndpoint = currentEndpointId ? endpoints.find((e)=>e.id === currentEndpointId) : null;
    if (currentEndpoint) {
        return `You are helping users explore an API. Generate 4 helpful question suggestions for the "${currentEndpoint.name}" endpoint.

Endpoint details:
- Name: ${currentEndpoint.name}
- Method: ${currentEndpoint.method}
- Path: ${currentEndpoint.path}
- Description: ${currentEndpoint.description || 'No description'}
- Parameters: ${currentEndpoint.parameters.join(', ') || 'None'}
- Has request body: ${currentEndpoint.hasBody}

Generate questions that help users:
1. Understand what this endpoint does
2. Know what parameters/data to send
3. See example requests or responses
4. Understand error handling or edge cases

Make questions specific to this endpoint, not generic.`;
    }
    // General suggestions based on the API
    const methodCounts = endpoints.reduce((acc, e)=>{
        acc[e.method] = (acc[e.method] || 0) + 1;
        return acc;
    }, {});
    const categories = [
        ...new Set(endpoints.flatMap((e)=>e.tags))
    ].slice(0, 5);
    return `You are helping users explore an API documentation. Generate 4 helpful starter question suggestions.

API Overview:
- Total endpoints: ${endpoints.length}
- Methods: ${Object.entries(methodCounts).map(([m, c])=>`${m}: ${c}`).join(', ')}
- Categories: ${categories.join(', ') || 'General'}

Sample endpoints:
${endpoints.slice(0, 8).map((e)=>`- ${e.method} ${e.name}: ${e.description || 'No description'}`).join('\n')}

Generate questions that help users:
1. Find the right endpoint for their use case
2. Understand authentication/authorization
3. Explore common operations (create, read, update, delete)
4. Get started quickly with the API

Make questions specific to this API's capabilities.`;
}
export async function POST(req) {
    try {
        const body = await req.json();
        const { endpointIndex, currentEndpointId } = body;
        // Generate hash-based cache key
        const cacheKey = generateCacheKey(endpointIndex, currentEndpointId);
        // Check KV cache first (1 week TTL)
        const cached = await CacheUtils.get(cacheKey);
        if (cached) {
            console.log(`[Suggestions API] Cache HIT: ${cacheKey}`);
            return Response.json({
                suggestions: cached,
                cached: true
            });
        }
        console.log(`[Suggestions API] Cache MISS: ${cacheKey}`);
        const apiKey = process.env.ANTHROPIC_API_KEY;
        if (!apiKey) {
            // Return fallback suggestions if no API key
            const fallback = currentEndpointId ? [
                {
                    title: 'What does this',
                    label: 'endpoint do?',
                    prompt: 'What does this endpoint do?'
                },
                {
                    title: 'What parameters',
                    label: 'are required?',
                    prompt: 'What parameters are required?'
                },
                {
                    title: 'Show me an',
                    label: 'example request',
                    prompt: 'Show me an example request'
                },
                {
                    title: 'What are the',
                    label: 'possible responses?',
                    prompt: 'What are the possible responses?'
                }
            ] : [
                {
                    title: 'Find endpoints',
                    label: 'for creating resources',
                    prompt: 'Find endpoints for creating resources'
                },
                {
                    title: 'How do I',
                    label: 'authenticate?',
                    prompt: 'How do I authenticate?'
                },
                {
                    title: 'What APIs are',
                    label: 'available?',
                    prompt: 'What APIs are available?'
                },
                {
                    title: 'Show me',
                    label: 'GET endpoints',
                    prompt: 'Show me all GET endpoints'
                }
            ];
            // Don't cache fallback suggestions - allow real suggestions to be generated later
            return Response.json({
                suggestions: fallback,
                cached: false,
                fallback: true
            });
        }
        const prompt = buildSuggestionPrompt(endpointIndex, currentEndpointId);
        const { object } = await generateObject({
            model: anthropic('claude-sonnet-4-20250514'),
            schema: SuggestionsSchema,
            prompt
        });
        // Cache the result in KV with 1 week TTL
        await CacheUtils.set(cacheKey, object.suggestions, CACHE_TTL_SECONDS, {
            log: true
        });
        return Response.json({
            suggestions: object.suggestions,
            cached: false
        });
    } catch (error) {
        console.error('[Suggestions API] Error:', error);
        // Return fallback on error
        const fallback = [
            {
                title: 'What APIs are',
                label: 'available?',
                prompt: 'What APIs are available?'
            },
            {
                title: 'How do I',
                label: 'authenticate?',
                prompt: 'How do I authenticate?'
            },
            {
                title: 'Find endpoints',
                label: 'for my use case',
                prompt: 'Help me find the right endpoint'
            },
            {
                title: 'Show me',
                label: 'examples',
                prompt: 'Show me some example requests'
            }
        ];
        return Response.json({
            suggestions: fallback,
            cached: false,
            error: true
        });
    }
}
