/**
 * GET /api/models - Fetch available models from OpenRouter
 */

import { NextResponse } from "next/server"

interface OpenRouterModel {
  id: string
  name: string
  created: number
  description: string
  context_length: number
  pricing: {
    prompt: string
    completion: string
  }
  top_provider?: {
    context_length: number
    max_completion_tokens?: number
    is_moderated: boolean
  }
}

export async function GET() {
  try {
    const response = await fetch('https://openrouter.ai/api/v1/models', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })

    if (!response.ok) {
      throw new Error(`OpenRouter API returned ${response.status}`)
    }

    const data = await response.json()
    
    // Filter and format models for our use case
    const models = data.data
      .filter((model: OpenRouterModel) => {
        // Only include chat models with reasonable pricing
        return model.pricing && 
               parseFloat(model.pricing.prompt) < 100 && // Max $100 per million tokens
               model.context_length >= 4096 // Minimum context window
      })
      .map((model: OpenRouterModel) => ({
        id: model.id,
        name: model.name,
        contextLength: model.context_length,
        promptPrice: model.pricing.prompt,
        completionPrice: model.pricing.completion,
        description: model.description,
      }))
      .sort((a: any, b: any) => {
        // Sort by popularity/price
        const aPrice = parseFloat(a.promptPrice)
        const bPrice = parseFloat(b.promptPrice)
        return aPrice - bPrice
      })

    return NextResponse.json({
      models,
      count: models.length,
      lastUpdated: new Date().toISOString(),
    })
  } catch (error) {
    console.error('Error fetching models:', error)
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch models',
        models: [],
        count: 0,
      },
      { status: 500 }
    )
  }
}

