// src/pages/api/ai/enhance-input.ts
import type { APIRoute } from 'astro';
import { withAPIAuth } from '../../../utils/auth.js';
import { apiError, apiServerError, createAuthErrorResponse } from '../../../utils/api.js';
import { enqueueApiCall } from '../../../utils/rateLimitedQueue.js';
import { aiService } from '../../../utils/aiService.js';
import { JSONParser } from '../../../utils/jsonUtils.js';
import { getPrompt } from '../../../config/prompts.js';

export const prerender = false;

const RATE_LIMIT_WINDOW_MS =
  Number.isFinite(parseInt(process.env.RATE_LIMIT_WINDOW_MS ?? '', 10))
    ? parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10)
    : 60_000; 

const RATE_LIMIT_MAX =
  Number.isFinite(parseInt(process.env.AI_RATE_LIMIT_MAX_REQUESTS ?? '', 10))
    ? parseInt(process.env.AI_RATE_LIMIT_MAX_REQUESTS!, 10)
    : 5;

const INPUT_MIN_CHARS = 40;
const INPUT_MAX_CHARS = 1000;
const Q_MIN_LEN = 15;
const Q_MAX_LEN = 160;
const Q_MAX_COUNT = 3;
const AI_TEMPERATURE = 0.3;
const CLEANER_TEMPERATURE = 0.0;

const rateLimitStore = new Map<string, { count: number; resetTime: number }>();

function checkRateLimit(userId: string): boolean {
  const now = Date.now();
  const entry = rateLimitStore.get(userId);
  if (!entry || now > entry.resetTime) {
    rateLimitStore.set(userId, { count: 1, resetTime: now + RATE_LIMIT_WINDOW_MS });
    return true;
  }
  if (entry.count >= RATE_LIMIT_MAX) return false;
  entry.count++;
  return true;
}

function cleanupExpiredRateLimits(): void {
  const now = Date.now();
  for (const [userId, entry] of rateLimitStore.entries()) {
    if (now > entry.resetTime) rateLimitStore.delete(userId);
  }
}
setInterval(cleanupExpiredRateLimits, 5 * 60 * 1000);

/**
 * Helpers
 */
function sanitizeInput(input: string): string {
  return input
    .replace(/```[\s\S]*?```/g, '[CODE_BLOCK_REMOVED]')
    .replace(/\<\/?[^>]+(>|$)/g, '')
    .replace(/\b(system|assistant|user)\s*[:]/gi, '[ROLE_REMOVED]')
    .replace(/\b(ignore|forget|disregard)\s+(previous|all|your)\s+(instructions?|context|rules?)/gi, '[INSTRUCTION_REMOVED]')
    .trim()
    .slice(0, INPUT_MAX_CHARS);
}

function stripJsonFences(s: string): string {
  return s.replace(/^```json\s*/i, '')
          .replace(/^```\s*/i, '')
          .replace(/\s*```\s*$/, '')
          .trim();
}

/**
 * Handler
 */
export const POST: APIRoute = async ({ request }) => {
  try {
    const auth = await withAPIAuth(request, 'ai');
    if (!auth.authenticated) return createAuthErrorResponse();
    const userId = auth.userId;

    if (!checkRateLimit(userId)) {
      return apiError.rateLimit('Enhancement rate limit exceeded');
    }

    const body = await request.json();
    const { input } = body;

    if (!input || typeof input !== 'string' || input.length < INPUT_MIN_CHARS) {
      return apiError.badRequest(`Input too short for enhancement (minimum ${INPUT_MIN_CHARS} characters)`);
    }

    const sanitizedInput = sanitizeInput(input);
    if (sanitizedInput.length < INPUT_MIN_CHARS) {
      return apiError.badRequest('Input too short after sanitization');
    }

    const taskId = `enhance_${userId}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
    const questionsPrompt = getPrompt('enhancementQuestions', sanitizedInput);

    console.log(`[ENHANCE-API] Processing enhancement request for user: ${userId}`);

    const aiResponse = await enqueueApiCall(
      () => aiService.callAI(questionsPrompt, { temperature: AI_TEMPERATURE }),
      taskId
    );

    if (!aiResponse?.content) {
      return apiServerError.unavailable('No enhancement response');
    }

    let parsed: unknown = JSONParser.safeParseJSON(stripJsonFences(aiResponse.content), null);

    let questions: string[] = Array.isArray(parsed) ? parsed : [];
    questions = questions
      .filter(q => typeof q === 'string')
      .map(q => q.trim())
      .filter(q => q.endsWith('?'))
      .filter(q => q.length >= Q_MIN_LEN && q.length <= Q_MAX_LEN)
      .slice(0, Q_MAX_COUNT);

    console.log(`[ENHANCE-API] User: ${userId}, Questions generated: ${questions.length}, Input length: ${sanitizedInput.length}`);

    return new Response(JSON.stringify({
      success: true,
      questions,
      taskId,
      inputComplete: questions.length === 0
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });

  } catch (err) {
    console.error('[ENHANCE-API] Enhancement error:', err);
    return apiServerError.internal('Enhancement processing failed');
  }
};
