import type { ChatMessage, APIResponse, AIAssistMessage } from "@/types"; export interface ZaiPlanConfig { apiKey?: string; generalEndpoint?: string; codingEndpoint?: string; } export class ZaiPlanService { private config: ZaiPlanConfig; constructor(config: ZaiPlanConfig = {}) { this.config = { generalEndpoint: config.generalEndpoint || "https://api.z.ai/api/paas/v4", codingEndpoint: config.codingEndpoint || "https://api.z.ai/api/coding/paas/v4", apiKey: config.apiKey || process.env.ZAI_API_KEY, }; } hasAuth(): boolean { return !!this.config.apiKey; } async validateConnection(): Promise> { try { if (!this.config.apiKey) { return { success: false, error: "API key is required" }; } const response = await fetch(`${this.config.generalEndpoint}/models`, { method: "GET", headers: this.getHeaders(), }); if (!response.ok) { if (response.status === 401) { return { success: false, error: "Invalid API key" }; } return { success: false, error: `Connection failed (${response.status}): ${response.statusText}` }; } const data = await response.json(); const models = data.data?.map((m: any) => m.id) || []; return { success: true, data: { valid: true, models } }; } catch (error) { const message = error instanceof Error ? error.message : "Connection failed"; if (message.includes("fetch")) { return { success: false, error: "Network error - check your internet connection" }; } return { success: false, error: message }; } } private getHeaders(): Record { return { "Content-Type": "application/json", "Authorization": `Bearer ${this.config.apiKey}`, "Accept-Language": "en-US,en", }; } async chatCompletion( messages: ChatMessage[], model: string = "glm-4.7", useCodingEndpoint: boolean = false ): Promise> { try { if (!this.config.apiKey) { throw new Error("API key is required. Please configure your Z.AI API key in settings."); } const endpoint = useCodingEndpoint ? this.config.codingEndpoint : this.config.generalEndpoint; console.log("[Z.AI] API call:", { endpoint, model, messages }); const response = await fetch(`${endpoint}/chat/completions`, { method: "POST", headers: this.getHeaders(), body: JSON.stringify({ model, messages, stream: false, }), }); console.log("[Z.AI] Response status:", response.status, response.statusText); if (!response.ok) { const errorText = await response.text(); console.error("[Z.AI] Error response:", errorText); throw new Error(`Chat completion failed (${response.status}): ${response.statusText} - ${errorText}`); } const data = await response.json(); console.log("[Z.AI] Response data:", data); if (data.choices && data.choices[0] && data.choices[0].message) { return { success: true, data: data.choices[0].message.content }; } else if (data.output && data.output.choices && data.output.choices[0]) { return { success: true, data: data.output.choices[0].message.content }; } else { return { success: false, error: "Unexpected response format" }; } } catch (error) { console.error("[Z.AI] Chat completion error:", error); return { success: false, error: error instanceof Error ? error.message : "Chat completion failed", }; } } async enhancePrompt(prompt: string, model?: string, options?: { toolCategory?: string; template?: string; diagnostics?: string }): Promise> { const toolCategory = options?.toolCategory || 'reasoning'; const template = options?.template || 'rtf'; const diagnostics = options?.diagnostics || ''; const toolSections: Record = { reasoning: '- Use full structured format with XML tags where helpful\n- Add explicit role assignment for complex tasks\n- Use numeric constraints over vague adjectives', thinking: '- CRITICAL: Short clean instructions ONLY\n- Do NOT add CoT or reasoning scaffolding — these models reason internally\n- State what you want, not how to think', openweight: '- Shorter prompts, simpler structure, no deep nesting\n- Direct linear instructions', agentic: '- Add Starting State + Target State + Allowed Actions + Forbidden Actions\n- Add Stop Conditions + Checkpoints after each step', ide: '- Add File path + Function name + Current Behavior + Desired Change + Scope lock', fullstack: '- Add Stack spec with version + what NOT to scaffold + component boundaries', image: '- Add Subject + Style + Mood + Lighting + Composition + Negative Prompts\n- Use tool-specific syntax (Midjourney comma-separated, DALL-E prose, SD weighted)', search: '- Specify mode: search vs analyze vs compare + citation requirements', }; const templateSections: Record = { rtf: 'Structure: Role (who) + Task (precise verb + what) + Format (exact output shape and length)', 'co-star': 'Structure: Context + Objective + Style + Tone + Audience + Response', risen: 'Structure: Role + Instructions + numbered Steps + End Goal + Narrowing constraints', crispe: 'Structure: Capacity + Role + Insight + Statement + Personality + Experiment/variants', cot: 'Add: "Think through this step by step before answering." Only for standard reasoning models, NOT for o1/o3/R1.', fewshot: 'Add 2-5 input/output examples wrapped in XML tags', filescope: 'Structure: File path + Function name + Current Behavior + Desired Change + Scope lock + Done When', react: 'Structure: Objective + Starting State + Target State + Allowed/Forbidden Actions + Stop Conditions + Checkpoints', visual: 'Structure: Subject + Action + Setting + Style + Mood + Lighting + Color Palette + Composition + Aspect Ratio + Negative Prompts', }; const toolSection = toolSections[toolCategory] || toolSections.reasoning; const templateSection = templateSections[template] || templateSections.rtf; const systemMessage: ChatMessage = { role: "system", content: `You are an expert prompt engineer using the PromptArch methodology. Enhance the user\'s prompt to be production-ready. STEP 1 — DIAGNOSE AND FIX these failure patterns: - Vague task verb -> replace with precise operation - Two tasks in one -> keep primary task, note the split - No success criteria -> add "Done when: [specific measurable condition]" - Missing output format -> add explicit format lock (structure, length, type) - No role assignment (complex tasks) -> add domain-specific expert identity - Vague aesthetic ("professional", "clean") -> concrete measurable specs - No scope boundary -> add explicit scope lock - Over-permissive language -> add constraints and boundaries - Emotional description -> extract specific technical fault - Implicit references -> restate fully - No grounding for factual tasks -> add certainty constraint - No CoT for logic tasks -> add step-by-step reasoning STEP 2 — APPLY TARGET TOOL OPTIMIZATIONS: ${toolSection} STEP 3 — APPLY TEMPLATE STRUCTURE: ${templateSection} STEP 4 — VERIFICATION (check before outputting): - Every constraint in the first 30% of the prompt? - MUST/NEVER over should/avoid? - Every sentence load-bearing with zero padding? - Format explicit with stated length? - Scope bounded? - Would this produce correct output on first try? STEP 5 — OUTPUT: Output ONLY the enhanced prompt. No explanations, no commentary, no markdown code fences. The prompt must be ready to paste directly into the target AI tool.${diagnostics ? '\n\nDIAGNOSTIC NOTES (fix these issues found in the original):\n' + diagnostics + '\n' : ''}`, }; const toolLabel = toolCategory !== 'reasoning' ? ` for ${toolCategory} AI tool` : ''; const userMessage: ChatMessage = { role: "user", content: `Enhance this prompt${toolLabel}:\n\n${prompt}`, }; return this.chatCompletion([systemMessage, userMessage], model || "${default_model}"); } async generateActionPlan(prd: string, model?: string): Promise> { const systemMessage: ChatMessage = { role: "system", content: `You are an expert technical lead and project manager. Generate a detailed action plan based on the PRD. Structure of action plan with: 1. Task breakdown with priorities (High/Medium/Low) 2. Dependencies between tasks 3. Estimated effort for each task 4. Recommended frameworks and technologies 5. Architecture guidelines and best practices Include specific recommendations for: - Frontend frameworks - Backend architecture - Database choices - Authentication/authorization - Deployment strategy`, }; const userMessage: ChatMessage = { role: "user", content: `Generate an action plan based on this PRD:\n\n${prd}`, }; return this.chatCompletion([systemMessage, userMessage], model || "glm-4.7", true); } async listModels(): Promise> { try { if (this.config.apiKey) { const response = await fetch(`${this.config.generalEndpoint}/models`, { headers: this.getHeaders(), }); if (!response.ok) { throw new Error(`Failed to list models: ${response.statusText}`); } const data = await response.json(); const models = data.data?.map((m: any) => m.id) || []; return { success: true, data: models }; } else { console.log("[Z.AI] No API key, using fallback models"); return { success: true, data: ["glm-4.7", "glm-4.6", "glm-4.5", "glm-4.5-air", "glm-4-flash", "glm-4-flashx"] }; } } catch (error) { console.error("[Z.AI] listModels error:", error); return { success: false, error: error instanceof Error ? error.message : "Failed to list models", }; } } getAvailableModels(): string[] { return ["glm-4.7", "glm-4.6", "glm-4.5", "glm-4.5-air", "glm-4-flash", "glm-4-flashx"]; } async generateUXDesignerPrompt(appDescription: string, model?: string): Promise> { const systemMessage: ChatMessage = { role: "system", content: `You are a world-class UX/UI designer with deep expertise in human-centered design principles, user research, interaction design, visual design systems, and modern design tools (Figma, Sketch, Adobe XD). Your task is to create an exceptional, detailed prompt for generating the best possible UX design for a given app description. Generate a comprehensive UX design prompt that includes: 1. USER RESEARCH & PERSONAS - Primary target users and their motivations - User pain points and needs - User journey maps - Persona archetypes with demographics and goals 2. INFORMATION ARCHITECTURE - Content hierarchy and organization - Navigation structure and patterns - User flows and key pathways - Site map or app structure 3. VISUAL DESIGN SYSTEM - Color palette recommendations (primary, secondary, accent, neutral) - Typography hierarchy and font pairings - Component library approach - Spacing, sizing, and layout grids - Iconography style and set 4. INTERACTION DESIGN - Micro-interactions and animations - Gesture patterns for touch interfaces - Loading states and empty states - Error handling and feedback mechanisms - Accessibility considerations (WCAG compliance) 5. KEY SCREENS & COMPONENTS - Core screens that need detailed design - Critical components (buttons, forms, cards, navigation) - Data visualization needs - Responsive design requirements (mobile, tablet, desktop) 6. DESIGN DELIVERABLES - Wireframes vs. high-fidelity mockups - Design system documentation needs - Prototyping requirements - Handoff specifications for developers 7. COMPETITIVE INSIGHTS - Design patterns from successful apps in this category - Opportunities to differentiate - Modern design trends to consider The output should be a detailed, actionable prompt that a designer or AI image generator can use to create world-class UX designs. Make the prompt specific, inspiring, and comprehensive. Use professional UX terminology.`, }; const userMessage: ChatMessage = { role: "user", content: `Create the BEST EVER UX design prompt for this app:\n\n${appDescription}`, }; return this.chatCompletion([systemMessage, userMessage], model || "glm-4.7", true); } async generateSlides( topic: string, options: { language?: string; theme?: string; slideCount?: number; audience?: string; organization?: string; animationStyle?: string; audienceStyle?: string; themeColors?: string[]; brandColors?: string[]; } = {}, model?: string ): Promise> { const { language = "English", theme = "executive-dark", slideCount = 10, audience = "Executives & C-Suite", organization = "", animationStyle = "Professional", audienceStyle = "Sophisticated, data-driven, strategic focus", themeColors = ["#09090b", "#6366f1", "#a855f7", "#fafafa"], brandColors = [] } = options; const [bgColor, primaryColor, secondaryColor, textColor] = themeColors; const brandColorStr = brandColors.length > 0 ? `\nBRAND COLORS TO USE: ${brandColors.join(", ")}` : ""; const systemMessage: ChatMessage = { role: "system", content: `You are a WORLD-CLASS presentation designer who creates STUNNING, AWARD-WINNING slide decks that rival McKinsey, Apple, and TED presentations. Your slides must be VISUALLY SPECTACULAR with: - Modern CSS3 animations (fade-in, slide-in, scale, parallax effects) - Sophisticated gradient backgrounds with depth - SVG charts and data visualizations inline - Glassmorphism and neumorphism effects - Professional typography with Inter/SF Pro fonts - Strategic use of whitespace - Micro-animations on hover/focus states - Progress indicators and visual hierarchy OUTPUT FORMAT - Return ONLY valid JSON: \`\`\`json { "title": "Presentation Title", "subtitle": "Compelling Subtitle", "theme": "${theme}", "language": "${language}", "slides": [ { "id": "slide-1", "title": "Slide Title", "content": "Plain text content summary", "htmlContent": "
FULL HTML with inline CSS and animations
", "notes": "Speaker notes", "layout": "title|content|two-column|chart|statistics|timeline|quote|comparison", "order": 1 } ] } \`\`\` DESIGN SYSTEM: - Primary: ${brandColors[0] || primaryColor} - Secondary: ${brandColors[1] || secondaryColor} - Background: ${bgColor} - Text: ${textColor}${brandColorStr} ANIMATION STYLE: ${animationStyle} - Professional: Subtle 0.3-0.5s ease transitions, fade and slide - Dynamic: 0.5-0.8s spring animations, emphasis effects, stagger delays - Impressive: Bold 0.8-1.2s animations, parallax, morphing, particle effects CSS ANIMATIONS TO INCLUDE: \`\`\`css @keyframes fadeInUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } } @keyframes slideInLeft { from { opacity: 0; transform: translateX(-50px); } to { opacity: 1; transform: translateX(0); } } @keyframes scaleIn { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: scale(1); } } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } } @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-10px); } } @keyframes gradientShift { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } \`\`\` SLIDE TYPES TO CREATE: 1. TITLE SLIDE: Hero-style with animated gradient background, large typography, subtle floating elements 2. AGENDA/OVERVIEW: Icon grid with staggered fade-in animations 3. DATA/CHARTS: Inline SVG bar/line/pie charts with animated drawing effects 4. KEY METRICS: Large animated numbers with counting effect styling, KPI cards with glassmorphism 5. TIMELINE: Horizontal/vertical timeline with sequential reveal animations 6. COMPARISON: Side-by-side cards with hover lift effects 7. QUOTE: Large typography with decorative quote marks, subtle background pattern 8. CALL-TO-ACTION: Bold CTA with pulsing button effect, clear next steps SVG CHART EXAMPLE: \`\`\`html \`\`\` TARGET AUDIENCE: ${audience} AUDIENCE STYLE: ${audienceStyle} ${organization ? `ORGANIZATION BRANDING: ${organization}` : ""} REQUIREMENTS: - ${slideCount > 0 ? `Create EXACTLY ${slideCount} slides` : "Maintain the exact number of slides/pages from the provided source presentation/document context. If no source file is provided, generate 10 slides by default."} - ALL content in ${language} - Each slide MUST have complete htmlContent with inline