import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

const INFERENCE_API_URL = process.env.INFERENCE_API_URL || 'http://localhost:8001';
// Pattern detection may take longer on large datasets
const INFERENCE_API_TIMEOUT = parseInt(process.env.INFERENCE_API_TIMEOUT || '60000', 10);

const CandleSchema = z.object({
  time: z.number(),
  open: z.number(),
  high: z.number(),
  low: z.number(),
  close: z.number(),
  volume: z.number().optional(),
});

const PatternDetectRequestSchema = z.object({
  candles: z.array(CandleSchema),
  patterns: z.array(z.string().min(1)),
});

export async function POST(request: NextRequest) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), INFERENCE_API_TIMEOUT);

  try {
    const body = await request.json();

    const result = PatternDetectRequestSchema.safeParse(body);
    if (!result.success) {
      clearTimeout(timeoutId);
      return NextResponse.json(
        { error: 'Invalid request', details: result.error.flatten() },
        { status: 400 }
      );
    }

    const validatedBody = result.data;

    const response = await fetch(`${INFERENCE_API_URL}/patterns/detect`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.API_KEY || '' },
      body: JSON.stringify(validatedBody),
      signal: controller.signal,
    });
    clearTimeout(timeoutId);

    const data = await response.json();
    if (!response.ok) {
      return NextResponse.json({ error: data.detail || 'Pattern detection failed' }, { status: response.status });
    }
    return NextResponse.json(data);
  } catch (error: any) {
    clearTimeout(timeoutId);
    if (error.name === 'AbortError') {
      return NextResponse.json({ error: 'Pattern detection timed out' }, { status: 504 });
    }
    if (error.cause?.code === 'ECONNREFUSED' || error.message?.includes('fetch failed')) {
      return NextResponse.json({ error: 'Inference service unavailable' }, { status: 503 });
    }
    console.error('patterns/detect proxy error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
