export type Complexity = 'low' | 'medium' | 'high' export interface AIAnalysisResponse { complexity: Complexity logicRules: string[] } import { BACKEND_URL } from "@/config/backend" export async function analyzeFeatureWithAI( featureName: string, description: string, requirements: string[], projectType?: string, userSelectedComplexity?: Complexity ): Promise { try { // Prefer dedicated analysis endpoint if available in requirements service const primaryUrl = `${BACKEND_URL}/api/ai/analyze-feature` const accessToken = (typeof window !== 'undefined') ? localStorage.getItem('accessToken') : null const headers: Record = { 'Content-Type': 'application/json' } if (accessToken) { headers.Authorization = `Bearer ${accessToken}` } let res = await fetch(primaryUrl, { method: 'POST', headers, body: JSON.stringify({ featureName, feature_name: featureName, // Backend expects this field name description, requirements, projectType, project_type: projectType, // Backend expects this field name complexity: userSelectedComplexity }), }) // If primary endpoint not found, fall back to mockup service to at least return deterministic hints if (res.status === 404) { const fallbackUrl = `${BACKEND_URL}/api/mockup/generate-wireframe` res = await fetch(fallbackUrl, { method: 'POST', headers, body: JSON.stringify({ prompt: `${featureName}: ${description}. Requirements: ${Array.isArray(requirements) ? requirements.join('; ') : 'No requirements provided'}`, device: 'desktop', }), }) } const text = await res.text() let json: any = {} try { json = text ? JSON.parse(text) : {} } catch { /* non-json */ } if (!res.ok) { throw new Error(json?.message || `AI request failed (${res.status})`) } // Map various backend shapes to AIAnalysisResponse if (json?.success && json?.analysis?.complexity && json?.analysis?.logicRules) { return { complexity: json.analysis.complexity as Complexity, logicRules: json.analysis.logicRules as string[] } } if (json?.success && json?.data?.complexity && json?.data?.logicRules) { return { complexity: json.data.complexity as Complexity, logicRules: json.data.logicRules as string[] } } if (json?.complexity && json?.logicRules) { return { complexity: json.complexity as Complexity, logicRules: json.logicRules as string[] } } // If mockup returns something else, provide sensible defaults return { complexity: userSelectedComplexity || 'medium', logicRules: [ 'Generated via fallback path; refine requirements for better analysis', 'Consider validation rules for key fields', ], } } catch (error) { // Fallback if the server route fails return { complexity: 'medium', logicRules: [ 'Unable to determine specific business rules due to insufficient requirements information', 'Generic logic implementation may be required', 'Basic validation rules should be considered', ], } } }