{"repo": "asshat1981ar/sdlca2a", "files": {"services/deepseekService.ts": {"a38e7ecc821956855aad5ef812edfda5871f6109": {"t": 1785746419.7837293, "n": 12206, "h": "71141bb3b85ae180", "c": "import { AppIdea, AppPlan, ChatMessage, ProjectFile, IdeationResult } from '../types.ts';\n\n// DeepSeek AI Service for collaborative coding\nclass DeepSeekService {\n private apiKey: string;\n private baseUrl: string = 'https://api.deepseek.com/v1';\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n private async makeRequest(endpoint: string, data: any): Promise {\n const response = await fetch(`${this.baseUrl}${endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.apiKey}`\n },\n body: JSON.stringify(data)\n });\n\n if (!response.ok) {\n throw new Error(`DeepSeek API error: ${response.status} ${response.statusText}`);\n }\n\n return await response.json();\n }\n\n async chat(messages: Array<{role: string, content: string}>, model: string = 'deepseek-coder'): Promise {\n try {\n const response = await this.makeRequest('/chat/completions', {\n model: model,\n messages: messages,\n temperature: 0.7,\n max_tokens: 4000,\n stream: false\n });\n\n return response.choices[0]?.message?.content || 'No response from DeepSeek';\n } catch (error) {\n console.error('DeepSeek chat error:', error);\n throw error;\n }\n }\n\n async performIdeation(idea: AppIdea): Promise {\n const messages = [\n {\n role: 'system',\n content: `You are a Product Strategist and Market Research Analyst. Analyze the user's application idea and provide competitor analysis and feature suggestions. Respond in JSON format with the structure:\n{\n \"competitors\": [{\"name\": \"\", \"description\": \"\", \"strengths\": [], \"weaknesses\": []}],\n \"differentiators\": [\"\"],\n \"featureSuggestions\": [\"\"]\n}`\n },\n {\n role: 'user',\n content: `Analyze this app idea and provide competitive landscape and feature suggestions: \"${idea.prompt}\"`\n }\n ];\n\n try {\n const response = await this.chat(messages, 'deepseek-r1');\n const parsed = this.parseJsonResponse(response);\n \n return parsed || {\n competitors: [\n {\n name: \"DeepSeek Analyzed Competitor\",\n description: \"AI-analyzed competitive solution\",\n strengths: [\"Market presence\", \"Established features\"],\n weaknesses: [\"Limited innovation\", \"User experience gaps\"]\n }\n ],\n differentiators: [\n \"AI-powered development approach\",\n \"Advanced automation capabilities\",\n \"Modern user experience\"\n ],\n featureSuggestions: [\n \"Intelligent code generation\",\n \"Real-time collaboration\",\n \"Advanced analytics dashboard\",\n \"Customizable workflows\",\n \"Smart automation\"\n ]\n };\n } catch (error) {\n console.error('DeepSeek ideation error:', error);\n throw error;\n }\n }\n\n async generateAppPlan(idea: AppIdea): Promise {\n const messages = [\n {\n role: 'system',\n content: `You are a Senior Software Architect. Create a comprehensive development plan for the given application idea. Respond in JSON format with the structure:\n{\n \"projectName\": \"\",\n \"description\": \"\",\n \"techStack\": {\"frontend\": [], \"backend\": [], \"database\": [], \"deployment\": []},\n \"fileStructure\": [{\"path\": \"\", \"type\": \"file|directory\", \"children\": []}]\n}`\n },\n {\n role: 'user',\n content: `Create a complete development plan for this application: \"${idea.prompt}\"`\n }\n ];\n\n try {\n const response = await this.chat(messages, 'deepseek-coder');\n const parsed = this.parseJsonResponse(response);\n \n return parsed || {\n projectName: idea.prompt.split(' ').slice(0, 3).join(' ') || \"DeepSeek Project\",\n description: `A ${idea.prompt.toLowerCase()} built with AI-assisted development.`,\n techStack: {\n frontend: [\"React\", \"TypeScript\", \"Tailwind CSS\"],\n backend: [\"Node.js\", \"Express\", \"FastAPI\"],\n database: [\"PostgreSQL\", \"Redis\"],\n deployment: [\"Docker\", \"Vercel\", \"AWS\"]\n },\n fileStructure: [\n {\n path: \"src\",\n type: \"directory\",\n children: [\n { path: \"src/index.tsx\", type: \"file\", children: [] },\n { path: \"src/App.tsx\", type: \"file\", children: [] },\n {\n path: \"src/components\",\n type: \"directory\",\n children: [\n { path: \"src/components/Header.tsx\", type: \"file\", children: [] },\n { path: \"src/components/Main.tsx\", type: \"file\", children: [] },\n { path: \"src/components/Footer.tsx\", type: \"file\", children: [] }\n ]\n },\n {\n path: \"src/services\",\n type: \"directory\",\n children: [\n { path: \"src/services/api.ts\", type: \"file\", children: [] },\n { path: \"src/services/auth.ts\", type: \"file\", children: [] }\n ]\n }\n ]\n },\n { path: \"package.json\", type: \"file\", children: [] },\n { path: \"tsconfig.json\", type: \"file\", children: [] },\n { path: \"tailwind.config.js\", type: \"file\", children: [] }\n ]\n };\n } catch (error) {\n console.error('DeepSeek plan generation error:', error);\n throw error;\n }\n }\n\n async generateCode(file: ProjectFile, plan: AppPlan, context: string = ''): Promise {\n const messages = [\n {\n role: 'system',\n content: `You are an expert software developer. Generate production-ready code for the specified file within the given project context. Only return the code, no explanations or markdown formatting.`\n },\n {\n role: 'user',\n content: `Generate code for file: ${file.path}\n \nProject: ${plan.projectName}\nDescription: ${plan.description}\nTech Stack: ${JSON.stringify(plan.techStack)}\nContext: ${context}\n\nGenerate clean, production-ready code for this file.`\n }\n ];\n\n try {\n const response = await this.chat(messages, 'deepseek-coder');\n return this.extractCode(response);\n } catch (error) {\n console.error('DeepSeek code generation error:', error);\n throw error;\n }\n }\n\n async chatWithContext(\n message: string, \n chatHistory: ChatMessage[], \n plan?: AppPlan, \n currentFile?: ProjectFile\n ): Promise {\n const systemMessage = {\n role: 'system',\n content: `You are an expert software development assistant. Help with coding, debugging, architecture, and development questions. Be concise and practical.`\n };\n\n let contextMessage = '';\n if (plan) {\n contextMessage += `\\nProject: ${plan.projectName} - ${plan.description}`;\n contextMessage += `\\nTech Stack: ${JSON.stringify(plan.techStack)}`;\n }\n if (currentFile) {\n contextMessage += `\\nCurrent File: ${currentFile.path}`;\n if (currentFile.code) {\n contextMessage += `\\nFile Content:\\n${currentFile.code}`;\n }\n }\n\n const messages = [\n systemMessage,\n ...(contextMessage ? [{role: 'user', content: `Context:${contextMessage}`}] : []),\n ...chatHistory.slice(-10).map(msg => ({\n role: msg.role === 'system' ? 'assistant' : msg.role,\n content: msg.content\n })),\n {role: 'user', content: message}\n ];\n\n try {\n return await this.chat(messages as any, 'deepseek-r1');\n } catch (error) {\n console.error('DeepSeek chat with context error:', error);\n throw error;\n }\n }\n\n async debugCode(code: string, errorMessage: string): Promise {\n const messages = [\n {\n role: 'system',\n content: 'You are a debugging expert. Analyze the code and error, then provide the fixed code. Only return the corrected code.'\n },\n {\n role: 'user',\n content: `Debug this code:\n\nCode:\n${code}\n\nError:\n${errorMessage}\n\nPlease provide the fixed code.`\n }\n ];\n\n try {\n const response = await this.chat(messages, 'deepseek-coder');\n return this.extractCode(response);\n } catch (error) {\n console.error('DeepSeek debug error:', error);\n throw error;\n }\n }\n\n async analyzeCode(files: ProjectFile[], plan?: AppPlan): Promise {\n const filesContext = files.map(f => `${f.path}:\\n${f.code || '// Empty file'}`).join('\\n\\n---\\n\\n');\n \n const messages = [\n {\n role: 'system',\n content: 'You are a senior code reviewer and architect. Analyze the codebase and provide insights about code quality, architecture, and suggestions for improvements.'\n },\n {\n role: 'user',\n content: `Analyze this codebase:\n\n${plan ? `Project: ${plan.projectName} - ${plan.description}` : ''}\n\nFiles:\n${filesContext}\n\nProvide analysis and recommendations.`\n }\n ];\n\n try {\n return await this.chat(messages, 'deepseek-r1');\n } catch (error) {\n console.error('DeepSeek analysis error:', error);\n throw error;\n }\n }\n\n private parseJsonResponse(text: string): T | null {\n let jsonStr = text.trim();\n \n // Remove markdown code blocks if present\n const fenceRegex = /^```(\\w*)?\\s*\\n?(.*?)\\n?\\s*```$/s;\n const match = jsonStr.match(fenceRegex);\n if (match && match[2]) {\n jsonStr = match[2].trim();\n }\n \n // Try to find JSON in the response\n const jsonMatch = jsonStr.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n jsonStr = jsonMatch[0];\n }\n \n try {\n return JSON.parse(jsonStr) as T;\n } catch (e) {\n console.error(\"Failed to parse JSON response:\", e, \"Original text:\", text);\n return null;\n }\n }\n\n private extractCode(text: string): string {\n let code = text.trim();\n \n // Remove markdown code blocks\n const fenceRegex = /^```(\\w*)?\\s*\\n?(.*?)\\n?\\s*```$/s;\n const match = code.match(fenceRegex);\n if (match && match[2]) {\n code = match[2].trim();\n }\n \n return code;\n }\n\n isConfigured(): boolean {\n return !!this.apiKey;\n }\n}\n\n// Initialize DeepSeek service\nconst DEEPSEEK_API_KEY = 'sk-ecd2dbd9e01e45e08cda7463083c3bbc';\nexport const deepseekService = new DeepSeekService(DEEPSEEK_API_KEY);\n\nexport const isDeepSeekConfigured = (): boolean => {\n return deepseekService.isConfigured();\n};"}}}}