1 line
45 KiB
JSON
1 line
45 KiB
JSON
{"repo": "azariacindy/mystudymate", "files": {"PBLMobile/app/Services/AIService.php": {"5acb426004d73914e72ce2271f7202be58cd914b": {"t": 1785746173.8940616, "n": 22100, "h": "14eb8fc6619360c9", "c": "<?php\n\nnamespace App\\Services;\n\nuse Illuminate\\Support\\Facades\\Http;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass AIService\n{\n protected $apiKey;\n protected $apiUrl;\n\n public function __construct()\n {\n $provider = env('AI_PROVIDER', 'openai');\n \n // Set API key based on provider\n if ($provider === 'gemini') {\n $this->apiKey = env('GEMINI_API_KEY');\n $this->apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent';\n } elseif ($provider === 'deepseek') {\n $this->apiKey = env('DEEPSEEK_API_KEY');\n $this->apiUrl = 'https://api.deepseek.com/v1/chat/completions';\n } else {\n $this->apiKey = env('OPENAI_API_KEY');\n $this->apiUrl = 'https://api.openai.com/v1/chat/completions';\n }\n }\n\n /**\n * Generate quiz questions from study notes using AI\n * \n * @param string $title\n * @param string $notes\n * @param int $questionCount\n * @param array $previousQuestions\n * @return array\n */\n public function generateQuiz($title, $notes, $questionCount = 5, $previousQuestions = [])\n {\n try {\n $prompt = $this->buildQuizPrompt($title, $notes, $questionCount, $previousQuestions);\n \n $provider = env('AI_PROVIDER', 'openai');\n \n if ($provider === 'gemini') {\n return $this->generateWithGemini($prompt);\n } elseif ($provider === 'deepseek') {\n return $this->generateWithDeepSeek($prompt);\n } else {\n return $this->generateWithOpenAI($prompt);\n }\n } catch (\\Exception $e) {\n Log::error('AI Service Error: ' . $e->getMessage());\n throw new \\Exception('Failed to generate quiz: ' . $e->getMessage());\n }\n }\n\n /**\n * Build prompt for quiz generation\n */\n private function buildQuizPrompt($title, $notes, $questionCount, $previousQuestions = [])\n {\n // Add randomization to ensure different questions each time\n $timestamp = time();\n $randomSeed = rand(1000, 9999);\n $variations = [\n 'Focus on different aspects and scenarios than typical questions',\n 'Create unique scenarios that haven\\'t been commonly asked',\n 'Explore edge cases and advanced implications',\n 'Cover different perspectives and use cases',\n 'Ask from various angles: implementation, debugging, architecture, optimization'\n ];\n $variation = $variations[array_rand($variations)];\n \n // Build previous questions warning\n $previousQuestionsText = '';\n if (!empty($previousQuestions)) {\n $previousQuestionsText = \"\\n\\n🚫 AVOID THESE PREVIOUSLY ASKED QUESTIONS:\\n\";\n foreach (array_slice($previousQuestions, 0, 10) as $index => $prevQ) {\n if (!empty($prevQ)) {\n $previousQuestionsText .= ($index + 1) . \". \" . substr($prevQ, 0, 150) . \"...\\n\";\n }\n }\n $previousQuestionsText .= \"\\n⚠️ Your questions MUST be COMPLETELY DIFFERENT from above!\\n\";\n }\n \n // Random question angles to force variety\n $angles = [\n 'Performance & Optimization perspective',\n 'Security & Best Practices angle', \n 'Architecture & Design Patterns view',\n 'Real-world Production Scenarios',\n 'Debugging & Troubleshooting focus',\n 'Scalability & Maintenance concerns',\n 'Edge Cases & Error Handling',\n 'Industry Standards & Modern Approaches'\n ];\n $selectedAngle = $angles[array_rand($angles)];\n \n // Random contexts to create variety\n $contexts = [\n 'a high-traffic e-commerce platform',\n 'a healthcare application with strict compliance',\n 'a real-time collaborative tool',\n 'a mobile app with offline capabilities',\n 'a data-intensive analytics dashboard',\n 'a microservices architecture system',\n 'a legacy system being modernized',\n 'a startup MVP needing rapid iteration'\n ];\n $context = $contexts[array_rand($contexts)];\n \n // Random constraints\n $constraints = [\n 'limited budget and tight deadline',\n 'must support 1M+ concurrent users',\n 'strict data privacy regulations',\n 'legacy code that cannot be fully rewritten',\n 'team has limited experience with technology',\n 'must maintain 99.99% uptime',\n 'operating in low-bandwidth environments',\n 'frequent requirement changes expected'\n ];\n $constraint = $constraints[array_rand($constraints)];\n \n return \"🎯 EXPERT QUIZ GENERATOR - UNIVERSITY LEVEL\n\nTOPIC: '{$title}'\nSESSION: {$timestamp}-{$randomSeed}\nREQUIRED: {$questionCount} ADVANCED QUESTIONS\nANGLE: {$selectedAngle}\nCONTEXT: Questions should involve scenarios in {$context}\nCONSTRAINT: Consider {$constraint}\nVARIATION STRATEGY: {$variation}\n{$previousQuestionsText}\n\n📖 CONTEXT (Use as starting point only, NOT limitation):\n{$notes}\n\n🔥 ABSOLUTE REQUIREMENTS - NO EXCEPTIONS:\n\n1. **FORBIDDEN QUESTION TYPES** (Will be rejected):\n ❌ \\\"What is the definition of...?\\\"\n ❌ \\\"Which of the following is...?\\\"\n ❌ \\\"The main purpose of X is...?\\\"\n ❌ Any question answerable by simple memorization\n ❌ Questions starting with \\\"What is\\\", \\\"Who invented\\\", \\\"When was\\\"\n \n2. **REQUIRED QUESTION COMPLEXITY**:\n ✅ MUST present a REAL SCENARIO with constraints\n ✅ MUST require analyzing trade-offs between options\n ✅ MUST test understanding of WHY, not just WHAT\n ✅ MUST involve decision-making in realistic context\n ✅ MUST have 2-3 viable solutions (not 1 obvious answer)\n\n3. **SCENARIO TEMPLATES** (Pick different ones each time):\n - \\\"A tech lead at [Company] needs to decide between [A] and [B] for [specific case]. Given [constraints], what's optimal?\\\"\n - \\\"During code review, you notice [pattern]. The team debates [approach X] vs [approach Y]. Considering [factors], which is better?\\\"\n - \\\"Production system shows [problem]. Analysis reveals [data]. What's the root cause and solution?\\\"\n - \\\"Implementing [feature] for [users/scale]. Three approaches proposed: [A], [B], [C]. Which handles [edge case] best?\\\"\n - \\\"Legacy system uses [old way]. Modernizing to [new way]. What migration strategy minimizes [risk]?\\\"\n\n4. **KNOWLEDGE EXPANSION** (Go WAY beyond notes):\n - If notes say \\\"Flutter basics\\\" → Ask about Widget lifecycle, State management patterns, Performance profiling\n - If notes say \\\"Database\\\" → Ask about Query optimization, Transaction isolation, Index strategies\n - If notes say \\\"API\\\" → Ask about Rate limiting, Caching strategies, Auth flows, Versioning\n - Assume student is preparing for PROFESSIONAL role, not just passing exam\n\n5. **DIFFICULTY CALIBRATION**:\n 🔴 HARD (40%): Requires synthesizing 3+ concepts, evaluating trade-offs, expert judgment\n 🟡 MEDIUM (40%): Requires applying concepts to new situations, comparing approaches\n 🟢 MEDIUM-EASY (20%): Foundational understanding with realistic complications\n\n For 5 questions specifically:\n - Q1: MEDIUM - Practical application with 1-2 constraints\n - Q2: HARD - Multi-factor analysis with competing concerns \n - Q3: MEDIUM - Comparison requiring deep understanding\n - Q4: HARD - Complex debugging or optimization problem\n - Q5: HARD - Architecture decision with long-term implications\n\n6. **DISTRACTOR ENGINEERING** (Critical for difficulty):\n All 4 options MUST be:\n - Technically plausible (not obviously wrong)\n - Sound correct to intermediate students\n - Based on common misconceptions or partial truths\n - Different enough to require analysis\n \n Example GOOD set:\n A) Correct in theory but fails at scale (10k+ users)\n B) Popular approach but has hidden security flaw\n C) ✓ BEST - Optimal balance of all factors\n D) Works perfectly but violates industry standards\n \n Example BAD set (FORBIDDEN):\n A) Completely impossible solution\n B) Joke answer or obviously wrong\n C) ✓ Only correct answer\n D) Contradicts basic facts\n \n3. **Question Coverage (Go BEYOND notes - VARY TOPICS EACH TIME):**\n - Industry Best Practices (even if not in notes)\n - Advanced Patterns and Architectures \n - Performance Optimization Strategies\n - Security Considerations\n - Scalability and Maintenance\n - Real Production Challenges\n - Modern Tools and Frameworks\n - Expert-level Decision Making\n \n ⚠️ IMPORTANT: Don't ask the same aspects every time!\n - If previous quiz focused on performance, now focus on security or architecture\n - Rotate between different knowledge areas\n - Cover breadth AND depth of the topic\n \n4. **Question Types (Mix These - VARY EACH QUIZ):**\n - Real-world Scenarios: Enterprise-level problems\n - Architecture Decisions: System design choices\n - Performance Analysis: Bottleneck identification\n - Code Review: Spot issues in complex scenarios\n - Best Practice Evaluation: When to use what\n - Debugging Complex Issues: Root cause analysis\n\n5. **Topic Expansion Strategy:**\n IF notes mention \\\"Flutter basics\\\" → Ask about Flutter architecture, state management, performance\n IF notes mention \\\"Database\\\" → Ask about indexing, normalization, query optimization, transactions\n IF notes mention \\\"API\\\" → Ask about RESTful design, authentication, rate limiting, caching\n IF notes mention \\\"Security\\\" → Ask about OWASP Top 10, encryption, authentication flows\n \n 💡 The notes are a STARTING POINT - expand to full professional-level knowledge!\n\n6. **CRITICAL: Distractor (Wrong Answer) Rules:**\n - ALL 4 options must sound CORRECT at first glance\n - Use SUBTLE differences between options\n - Include answers that are \\\"partially correct\\\" but not optimal\n - Each wrong answer should appeal to different misconceptions\n - NO obviously wrong/silly options\n - Make students doubt their answer and reconsider\n \n Example of GOOD distractors:\n ✅ Option A: Correct in theory but fails in edge case\n ✅ Option B: Common practice but not best practice \n ✅ Option C: CORRECT - Best solution overall\n ✅ Option D: Works but has hidden drawback\n \n Example of BAD distractors (AVOID):\n ❌ Option A: Completely unrelated answer\n ❌ Option B: Obviously impossible solution\n ❌ Option C: Joke answer\n ❌ Option D: Too simple/basic\n\n7. **Question Complexity:**\n - Use multi-step reasoning (requires 2-3 mental steps)\n - Include constraints that eliminate obvious choices\n - Test understanding of trade-offs and edge cases\n - Require weighing pros/cons of multiple valid approaches\n - Make correct answer not immediately obvious\n\n8. **Answer Crafting Strategy:**\n - Write 4 options that ALL could theoretically work\n - Then add subtle reason why 3 are suboptimal\n - Correct answer should be \\\"best\\\" not \\\"only\\\" solution\n - Force students to analyze WHY one is better than others\n\nGenerate exactly {$questionCount} questions in JSON format:\n[\n {\n \\\"question\\\": \\\"[Complex scenario with specific constraints and context]\\\",\n \\\"options\\\": [\n \\\"[Option that works but has performance trade-off]\\\",\n \\\"[Popular approach but not optimal for this case]\\\",\n \\\"[Correct - Best balance of all factors]\\\",\n \\\"[Technically correct but violates best practices]\\\"\n ],\n \\\"correct_answer\\\": 2,\n \\\"explanation\\\": \\\"[Detailed: Why option 3 is BEST + Why option 1 fails in X scenario + Why option 2 is suboptimal + Why option 4 has hidden issue + Core principle explanation]\\\"\n }\n]\n\n📊 MANDATORY VARIETY RULES:\n\nFor EACH question in this quiz:\n1. Use DIFFERENT scenario type (don't repeat same format)\n2. Test DIFFERENT aspect of topic (performance vs security vs architecture)\n3. Use DIFFERENT companies/contexts (startup vs enterprise vs legacy system)\n4. Focus on DIFFERENT skill level (Q1: application, Q2: analysis, Q3: evaluation, Q4: synthesis, Q5: creation)\n\n🎯 SELF-VALIDATION (You MUST pass all checks):\n- [ ] Zero questions start with \\\"What is\\\" or \\\"Which of the following\\\"\n- [ ] Every question has a realistic scenario with constraints\n- [ ] All 4 options sound correct to someone with surface knowledge\n- [ ] Correct answer is \\\"best\\\" not \\\"only\\\" solution\n- [ ] At least 2 options are partially correct in different contexts\n- [ ] Explanation covers WHY each wrong answer fails in THIS scenario\n- [ ] Questions cover 5 DIFFERENT aspects of '{$title}'\n- [ ] No two questions test the same knowledge point\n- [ ] Reading notes alone would NOT be enough to answer confidently\n- [ ] Would take experienced developer 30+ seconds per question\n\n⚠️ DIFFICULTY TEST: If you think \\\"this is too hard\\\" → It's probably right difficulty!\n\n🚨 FINAL WARNING: If I see \\\"What is...\\\", \\\"Define...\\\", or simple factual questions, START OVER!\n\nReturn ONLY valid JSON array, no markdown code blocks or additional text.\";\n }\n\n /**\n * Generate quiz using OpenAI\n */\n private function generateWithOpenAI($prompt)\n {\n $response = Http::withHeaders([\n 'Authorization' => 'Bearer ' . $this->apiKey,\n 'Content-Type' => 'application/json',\n ])->timeout(60)->post($this->apiUrl, [\n 'model' => env('OPENAI_MODEL', 'gpt-4'), // Use GPT-4 for better quality\n 'messages' => [\n [\n 'role' => 'system',\n 'content' => 'You are an expert university-level quiz creator specializing in challenging, scenario-based questions that test deep understanding. Always create varied, non-repetitive questions.'\n ],\n [\n 'role' => 'user',\n 'content' => $prompt\n ]\n ],\n 'temperature' => 1.1,\n 'max_tokens' => 8000,\n 'presence_penalty' => 0.6, // Discourage repetition\n 'frequency_penalty' => 0.3, // Reduce repeating patterns\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('OpenAI API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['choices'][0]['message']['content'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Generate quiz using Google Gemini\n */\n private function generateWithGemini($prompt)\n {\n $response = Http::timeout(60)->post($this->apiUrl . '?key=' . $this->apiKey, [\n 'contents' => [\n [\n 'parts' => [\n ['text' => $prompt]\n ]\n ]\n ],\n 'generationConfig' => [\n 'temperature' => 1.2, // Higher = more creative and varied\n 'maxOutputTokens' => 8000, // More space for complex questions\n 'topP' => 0.95, // Nucleus sampling for diversity\n 'topK' => 64, // Increased for more variety\n ]\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('Gemini API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Generate quiz using DeepSeek\n */\n private function generateWithDeepSeek($prompt)\n {\n $response = Http::withHeaders([\n 'Authorization' => 'Bearer ' . $this->apiKey,\n 'Content-Type' => 'application/json',\n ])->timeout(90)->post($this->apiUrl, [\n 'model' => env('DEEPSEEK_MODEL', 'deepseek-chat'),\n 'messages' => [\n [\n 'role' => 'system',\n 'content' => 'You are an expert university-level quiz creator specializing in challenging, scenario-based questions that test deep understanding. Always create varied, non-repetitive questions. Return ONLY valid JSON format.'\n ],\n [\n 'role' => 'user',\n 'content' => $prompt\n ]\n ],\n 'temperature' => 1.2,\n 'max_tokens' => 8000,\n 'top_p' => 0.95,\n 'frequency_penalty' => 0.5,\n 'presence_penalty' => 0.5,\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('DeepSeek API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['choices'][0]['message']['content'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Parse AI response and extract JSON\n */\n private function parseQuizResponse($content)\n {\n // Remove markdown code blocks if present\n $content = preg_replace('/```json\\s*/i', '', $content);\n $content = preg_replace('/```\\s*$/', '', $content);\n $content = trim($content);\n\n // Try to find JSON array\n if (preg_match('/\\[\\s*\\{.*?\\}\\s*\\]/s', $content, $matches)) {\n $content = $matches[0];\n }\n\n $questions = json_decode($content, true);\n\n if (json_last_error() !== JSON_ERROR_NONE) {\n throw new \\Exception('Invalid JSON response from AI: ' . json_last_error_msg());\n }\n\n if (!is_array($questions)) {\n throw new \\Exception('AI response is not an array');\n }\n\n // Validate question structure\n foreach ($questions as $index => $question) {\n if (!isset($question['question']) || !isset($question['options']) || !isset($question['correct_answer'])) {\n throw new \\Exception(\"Invalid question structure at index {$index}\");\n }\n\n if (!is_array($question['options']) || count($question['options']) < 2) {\n throw new \\Exception(\"Invalid options at index {$index}\");\n }\n }\n\n return $questions;\n }\n\n /**\n * Generate fallback quiz if AI fails\n */\n public function generateFallbackQuiz($title, $notes)\n {\n $noteExcerpt = substr($notes, 0, 100);\n \n return [\n [\n 'question' => \"Based on your understanding of {$title}, which approach would be most effective in a production environment?\",\n 'options' => [\n \"Focus only on basic implementation without considering edge cases\",\n \"Implement with comprehensive error handling and scalability in mind\",\n \"Use the simplest solution without documentation\",\n \"Copy solutions from tutorials without understanding\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"Production systems require comprehensive error handling, scalability considerations, and proper documentation to ensure long-term maintainability and reliability.\"\n ],\n [\n 'question' => \"When implementing {$title}, what is the most critical factor to consider first?\",\n 'options' => [\n \"Code aesthetics and formatting\",\n \"System architecture and design patterns\",\n \"Using the latest trending libraries\",\n \"Writing code as quickly as possible\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"System architecture and design patterns should be considered first as they form the foundation that affects all subsequent implementation decisions and long-term maintainability.\"\n ],\n [\n 'question' => \"In the context of {$title}, how should you handle performance optimization?\",\n 'options' => [\n \"Optimize everything from the start even without bottlenecks\",\n \"Profile first, identify bottlenecks, then optimize strategically\",\n \"Never optimize, it's premature optimization\",\n \"Only optimize when users complain\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"The best practice is to profile first to identify actual bottlenecks, then optimize strategically based on data. This prevents wasted effort on non-issues while addressing real performance problems.\"\n ],\n [\n 'question' => \"What testing strategy is most appropriate for {$title}?\",\n 'options' => [\n \"Only manual testing when features are complete\",\n \"Comprehensive unit, integration, and end-to-end testing\",\n \"No testing, just deploy and fix bugs later\",\n \"Only test the happy path scenarios\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"A comprehensive testing strategy with unit tests, integration tests, and end-to-end tests provides the best coverage and catches issues at different levels, reducing bugs in production.\"\n ],\n [\n 'question' => \"When maintaining code related to {$title}, what principle should guide your decisions?\",\n 'options' => [\n \"Always rewrite everything with new technologies\",\n \"Balance between technical debt, business needs, and code quality\",\n \"Never change working code regardless of quality\",\n \"Prioritize speed over all other considerations\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"Effective code maintenance requires balancing technical debt management with business requirements and code quality. This pragmatic approach ensures sustainable development while meeting business objectives.\"\n ]\n ];\n }\n}\n"}, "8bf021f0adf0aa4c048c82a3be2e9085f00117d0": {"t": 1785760320.9251084, "n": 22100, "h": "14eb8fc6619360c9", "c": "<?php\n\nnamespace App\\Services;\n\nuse Illuminate\\Support\\Facades\\Http;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass AIService\n{\n protected $apiKey;\n protected $apiUrl;\n\n public function __construct()\n {\n $provider = env('AI_PROVIDER', 'openai');\n \n // Set API key based on provider\n if ($provider === 'gemini') {\n $this->apiKey = env('GEMINI_API_KEY');\n $this->apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent';\n } elseif ($provider === 'deepseek') {\n $this->apiKey = env('DEEPSEEK_API_KEY');\n $this->apiUrl = 'https://api.deepseek.com/v1/chat/completions';\n } else {\n $this->apiKey = env('OPENAI_API_KEY');\n $this->apiUrl = 'https://api.openai.com/v1/chat/completions';\n }\n }\n\n /**\n * Generate quiz questions from study notes using AI\n * \n * @param string $title\n * @param string $notes\n * @param int $questionCount\n * @param array $previousQuestions\n * @return array\n */\n public function generateQuiz($title, $notes, $questionCount = 5, $previousQuestions = [])\n {\n try {\n $prompt = $this->buildQuizPrompt($title, $notes, $questionCount, $previousQuestions);\n \n $provider = env('AI_PROVIDER', 'openai');\n \n if ($provider === 'gemini') {\n return $this->generateWithGemini($prompt);\n } elseif ($provider === 'deepseek') {\n return $this->generateWithDeepSeek($prompt);\n } else {\n return $this->generateWithOpenAI($prompt);\n }\n } catch (\\Exception $e) {\n Log::error('AI Service Error: ' . $e->getMessage());\n throw new \\Exception('Failed to generate quiz: ' . $e->getMessage());\n }\n }\n\n /**\n * Build prompt for quiz generation\n */\n private function buildQuizPrompt($title, $notes, $questionCount, $previousQuestions = [])\n {\n // Add randomization to ensure different questions each time\n $timestamp = time();\n $randomSeed = rand(1000, 9999);\n $variations = [\n 'Focus on different aspects and scenarios than typical questions',\n 'Create unique scenarios that haven\\'t been commonly asked',\n 'Explore edge cases and advanced implications',\n 'Cover different perspectives and use cases',\n 'Ask from various angles: implementation, debugging, architecture, optimization'\n ];\n $variation = $variations[array_rand($variations)];\n \n // Build previous questions warning\n $previousQuestionsText = '';\n if (!empty($previousQuestions)) {\n $previousQuestionsText = \"\\n\\n🚫 AVOID THESE PREVIOUSLY ASKED QUESTIONS:\\n\";\n foreach (array_slice($previousQuestions, 0, 10) as $index => $prevQ) {\n if (!empty($prevQ)) {\n $previousQuestionsText .= ($index + 1) . \". \" . substr($prevQ, 0, 150) . \"...\\n\";\n }\n }\n $previousQuestionsText .= \"\\n⚠️ Your questions MUST be COMPLETELY DIFFERENT from above!\\n\";\n }\n \n // Random question angles to force variety\n $angles = [\n 'Performance & Optimization perspective',\n 'Security & Best Practices angle', \n 'Architecture & Design Patterns view',\n 'Real-world Production Scenarios',\n 'Debugging & Troubleshooting focus',\n 'Scalability & Maintenance concerns',\n 'Edge Cases & Error Handling',\n 'Industry Standards & Modern Approaches'\n ];\n $selectedAngle = $angles[array_rand($angles)];\n \n // Random contexts to create variety\n $contexts = [\n 'a high-traffic e-commerce platform',\n 'a healthcare application with strict compliance',\n 'a real-time collaborative tool',\n 'a mobile app with offline capabilities',\n 'a data-intensive analytics dashboard',\n 'a microservices architecture system',\n 'a legacy system being modernized',\n 'a startup MVP needing rapid iteration'\n ];\n $context = $contexts[array_rand($contexts)];\n \n // Random constraints\n $constraints = [\n 'limited budget and tight deadline',\n 'must support 1M+ concurrent users',\n 'strict data privacy regulations',\n 'legacy code that cannot be fully rewritten',\n 'team has limited experience with technology',\n 'must maintain 99.99% uptime',\n 'operating in low-bandwidth environments',\n 'frequent requirement changes expected'\n ];\n $constraint = $constraints[array_rand($constraints)];\n \n return \"🎯 EXPERT QUIZ GENERATOR - UNIVERSITY LEVEL\n\nTOPIC: '{$title}'\nSESSION: {$timestamp}-{$randomSeed}\nREQUIRED: {$questionCount} ADVANCED QUESTIONS\nANGLE: {$selectedAngle}\nCONTEXT: Questions should involve scenarios in {$context}\nCONSTRAINT: Consider {$constraint}\nVARIATION STRATEGY: {$variation}\n{$previousQuestionsText}\n\n📖 CONTEXT (Use as starting point only, NOT limitation):\n{$notes}\n\n🔥 ABSOLUTE REQUIREMENTS - NO EXCEPTIONS:\n\n1. **FORBIDDEN QUESTION TYPES** (Will be rejected):\n ❌ \\\"What is the definition of...?\\\"\n ❌ \\\"Which of the following is...?\\\"\n ❌ \\\"The main purpose of X is...?\\\"\n ❌ Any question answerable by simple memorization\n ❌ Questions starting with \\\"What is\\\", \\\"Who invented\\\", \\\"When was\\\"\n \n2. **REQUIRED QUESTION COMPLEXITY**:\n ✅ MUST present a REAL SCENARIO with constraints\n ✅ MUST require analyzing trade-offs between options\n ✅ MUST test understanding of WHY, not just WHAT\n ✅ MUST involve decision-making in realistic context\n ✅ MUST have 2-3 viable solutions (not 1 obvious answer)\n\n3. **SCENARIO TEMPLATES** (Pick different ones each time):\n - \\\"A tech lead at [Company] needs to decide between [A] and [B] for [specific case]. Given [constraints], what's optimal?\\\"\n - \\\"During code review, you notice [pattern]. The team debates [approach X] vs [approach Y]. Considering [factors], which is better?\\\"\n - \\\"Production system shows [problem]. Analysis reveals [data]. What's the root cause and solution?\\\"\n - \\\"Implementing [feature] for [users/scale]. Three approaches proposed: [A], [B], [C]. Which handles [edge case] best?\\\"\n - \\\"Legacy system uses [old way]. Modernizing to [new way]. What migration strategy minimizes [risk]?\\\"\n\n4. **KNOWLEDGE EXPANSION** (Go WAY beyond notes):\n - If notes say \\\"Flutter basics\\\" → Ask about Widget lifecycle, State management patterns, Performance profiling\n - If notes say \\\"Database\\\" → Ask about Query optimization, Transaction isolation, Index strategies\n - If notes say \\\"API\\\" → Ask about Rate limiting, Caching strategies, Auth flows, Versioning\n - Assume student is preparing for PROFESSIONAL role, not just passing exam\n\n5. **DIFFICULTY CALIBRATION**:\n 🔴 HARD (40%): Requires synthesizing 3+ concepts, evaluating trade-offs, expert judgment\n 🟡 MEDIUM (40%): Requires applying concepts to new situations, comparing approaches\n 🟢 MEDIUM-EASY (20%): Foundational understanding with realistic complications\n\n For 5 questions specifically:\n - Q1: MEDIUM - Practical application with 1-2 constraints\n - Q2: HARD - Multi-factor analysis with competing concerns \n - Q3: MEDIUM - Comparison requiring deep understanding\n - Q4: HARD - Complex debugging or optimization problem\n - Q5: HARD - Architecture decision with long-term implications\n\n6. **DISTRACTOR ENGINEERING** (Critical for difficulty):\n All 4 options MUST be:\n - Technically plausible (not obviously wrong)\n - Sound correct to intermediate students\n - Based on common misconceptions or partial truths\n - Different enough to require analysis\n \n Example GOOD set:\n A) Correct in theory but fails at scale (10k+ users)\n B) Popular approach but has hidden security flaw\n C) ✓ BEST - Optimal balance of all factors\n D) Works perfectly but violates industry standards\n \n Example BAD set (FORBIDDEN):\n A) Completely impossible solution\n B) Joke answer or obviously wrong\n C) ✓ Only correct answer\n D) Contradicts basic facts\n \n3. **Question Coverage (Go BEYOND notes - VARY TOPICS EACH TIME):**\n - Industry Best Practices (even if not in notes)\n - Advanced Patterns and Architectures \n - Performance Optimization Strategies\n - Security Considerations\n - Scalability and Maintenance\n - Real Production Challenges\n - Modern Tools and Frameworks\n - Expert-level Decision Making\n \n ⚠️ IMPORTANT: Don't ask the same aspects every time!\n - If previous quiz focused on performance, now focus on security or architecture\n - Rotate between different knowledge areas\n - Cover breadth AND depth of the topic\n \n4. **Question Types (Mix These - VARY EACH QUIZ):**\n - Real-world Scenarios: Enterprise-level problems\n - Architecture Decisions: System design choices\n - Performance Analysis: Bottleneck identification\n - Code Review: Spot issues in complex scenarios\n - Best Practice Evaluation: When to use what\n - Debugging Complex Issues: Root cause analysis\n\n5. **Topic Expansion Strategy:**\n IF notes mention \\\"Flutter basics\\\" → Ask about Flutter architecture, state management, performance\n IF notes mention \\\"Database\\\" → Ask about indexing, normalization, query optimization, transactions\n IF notes mention \\\"API\\\" → Ask about RESTful design, authentication, rate limiting, caching\n IF notes mention \\\"Security\\\" → Ask about OWASP Top 10, encryption, authentication flows\n \n 💡 The notes are a STARTING POINT - expand to full professional-level knowledge!\n\n6. **CRITICAL: Distractor (Wrong Answer) Rules:**\n - ALL 4 options must sound CORRECT at first glance\n - Use SUBTLE differences between options\n - Include answers that are \\\"partially correct\\\" but not optimal\n - Each wrong answer should appeal to different misconceptions\n - NO obviously wrong/silly options\n - Make students doubt their answer and reconsider\n \n Example of GOOD distractors:\n ✅ Option A: Correct in theory but fails in edge case\n ✅ Option B: Common practice but not best practice \n ✅ Option C: CORRECT - Best solution overall\n ✅ Option D: Works but has hidden drawback\n \n Example of BAD distractors (AVOID):\n ❌ Option A: Completely unrelated answer\n ❌ Option B: Obviously impossible solution\n ❌ Option C: Joke answer\n ❌ Option D: Too simple/basic\n\n7. **Question Complexity:**\n - Use multi-step reasoning (requires 2-3 mental steps)\n - Include constraints that eliminate obvious choices\n - Test understanding of trade-offs and edge cases\n - Require weighing pros/cons of multiple valid approaches\n - Make correct answer not immediately obvious\n\n8. **Answer Crafting Strategy:**\n - Write 4 options that ALL could theoretically work\n - Then add subtle reason why 3 are suboptimal\n - Correct answer should be \\\"best\\\" not \\\"only\\\" solution\n - Force students to analyze WHY one is better than others\n\nGenerate exactly {$questionCount} questions in JSON format:\n[\n {\n \\\"question\\\": \\\"[Complex scenario with specific constraints and context]\\\",\n \\\"options\\\": [\n \\\"[Option that works but has performance trade-off]\\\",\n \\\"[Popular approach but not optimal for this case]\\\",\n \\\"[Correct - Best balance of all factors]\\\",\n \\\"[Technically correct but violates best practices]\\\"\n ],\n \\\"correct_answer\\\": 2,\n \\\"explanation\\\": \\\"[Detailed: Why option 3 is BEST + Why option 1 fails in X scenario + Why option 2 is suboptimal + Why option 4 has hidden issue + Core principle explanation]\\\"\n }\n]\n\n📊 MANDATORY VARIETY RULES:\n\nFor EACH question in this quiz:\n1. Use DIFFERENT scenario type (don't repeat same format)\n2. Test DIFFERENT aspect of topic (performance vs security vs architecture)\n3. Use DIFFERENT companies/contexts (startup vs enterprise vs legacy system)\n4. Focus on DIFFERENT skill level (Q1: application, Q2: analysis, Q3: evaluation, Q4: synthesis, Q5: creation)\n\n🎯 SELF-VALIDATION (You MUST pass all checks):\n- [ ] Zero questions start with \\\"What is\\\" or \\\"Which of the following\\\"\n- [ ] Every question has a realistic scenario with constraints\n- [ ] All 4 options sound correct to someone with surface knowledge\n- [ ] Correct answer is \\\"best\\\" not \\\"only\\\" solution\n- [ ] At least 2 options are partially correct in different contexts\n- [ ] Explanation covers WHY each wrong answer fails in THIS scenario\n- [ ] Questions cover 5 DIFFERENT aspects of '{$title}'\n- [ ] No two questions test the same knowledge point\n- [ ] Reading notes alone would NOT be enough to answer confidently\n- [ ] Would take experienced developer 30+ seconds per question\n\n⚠️ DIFFICULTY TEST: If you think \\\"this is too hard\\\" → It's probably right difficulty!\n\n🚨 FINAL WARNING: If I see \\\"What is...\\\", \\\"Define...\\\", or simple factual questions, START OVER!\n\nReturn ONLY valid JSON array, no markdown code blocks or additional text.\";\n }\n\n /**\n * Generate quiz using OpenAI\n */\n private function generateWithOpenAI($prompt)\n {\n $response = Http::withHeaders([\n 'Authorization' => 'Bearer ' . $this->apiKey,\n 'Content-Type' => 'application/json',\n ])->timeout(60)->post($this->apiUrl, [\n 'model' => env('OPENAI_MODEL', 'gpt-4'), // Use GPT-4 for better quality\n 'messages' => [\n [\n 'role' => 'system',\n 'content' => 'You are an expert university-level quiz creator specializing in challenging, scenario-based questions that test deep understanding. Always create varied, non-repetitive questions.'\n ],\n [\n 'role' => 'user',\n 'content' => $prompt\n ]\n ],\n 'temperature' => 1.1,\n 'max_tokens' => 8000,\n 'presence_penalty' => 0.6, // Discourage repetition\n 'frequency_penalty' => 0.3, // Reduce repeating patterns\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('OpenAI API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['choices'][0]['message']['content'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Generate quiz using Google Gemini\n */\n private function generateWithGemini($prompt)\n {\n $response = Http::timeout(60)->post($this->apiUrl . '?key=' . $this->apiKey, [\n 'contents' => [\n [\n 'parts' => [\n ['text' => $prompt]\n ]\n ]\n ],\n 'generationConfig' => [\n 'temperature' => 1.2, // Higher = more creative and varied\n 'maxOutputTokens' => 8000, // More space for complex questions\n 'topP' => 0.95, // Nucleus sampling for diversity\n 'topK' => 64, // Increased for more variety\n ]\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('Gemini API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Generate quiz using DeepSeek\n */\n private function generateWithDeepSeek($prompt)\n {\n $response = Http::withHeaders([\n 'Authorization' => 'Bearer ' . $this->apiKey,\n 'Content-Type' => 'application/json',\n ])->timeout(90)->post($this->apiUrl, [\n 'model' => env('DEEPSEEK_MODEL', 'deepseek-chat'),\n 'messages' => [\n [\n 'role' => 'system',\n 'content' => 'You are an expert university-level quiz creator specializing in challenging, scenario-based questions that test deep understanding. Always create varied, non-repetitive questions. Return ONLY valid JSON format.'\n ],\n [\n 'role' => 'user',\n 'content' => $prompt\n ]\n ],\n 'temperature' => 1.2,\n 'max_tokens' => 8000,\n 'top_p' => 0.95,\n 'frequency_penalty' => 0.5,\n 'presence_penalty' => 0.5,\n ]);\n\n if (!$response->successful()) {\n throw new \\Exception('DeepSeek API error: ' . $response->body());\n }\n\n $data = $response->json();\n $content = $data['choices'][0]['message']['content'] ?? '';\n \n return $this->parseQuizResponse($content);\n }\n\n /**\n * Parse AI response and extract JSON\n */\n private function parseQuizResponse($content)\n {\n // Remove markdown code blocks if present\n $content = preg_replace('/```json\\s*/i', '', $content);\n $content = preg_replace('/```\\s*$/', '', $content);\n $content = trim($content);\n\n // Try to find JSON array\n if (preg_match('/\\[\\s*\\{.*?\\}\\s*\\]/s', $content, $matches)) {\n $content = $matches[0];\n }\n\n $questions = json_decode($content, true);\n\n if (json_last_error() !== JSON_ERROR_NONE) {\n throw new \\Exception('Invalid JSON response from AI: ' . json_last_error_msg());\n }\n\n if (!is_array($questions)) {\n throw new \\Exception('AI response is not an array');\n }\n\n // Validate question structure\n foreach ($questions as $index => $question) {\n if (!isset($question['question']) || !isset($question['options']) || !isset($question['correct_answer'])) {\n throw new \\Exception(\"Invalid question structure at index {$index}\");\n }\n\n if (!is_array($question['options']) || count($question['options']) < 2) {\n throw new \\Exception(\"Invalid options at index {$index}\");\n }\n }\n\n return $questions;\n }\n\n /**\n * Generate fallback quiz if AI fails\n */\n public function generateFallbackQuiz($title, $notes)\n {\n $noteExcerpt = substr($notes, 0, 100);\n \n return [\n [\n 'question' => \"Based on your understanding of {$title}, which approach would be most effective in a production environment?\",\n 'options' => [\n \"Focus only on basic implementation without considering edge cases\",\n \"Implement with comprehensive error handling and scalability in mind\",\n \"Use the simplest solution without documentation\",\n \"Copy solutions from tutorials without understanding\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"Production systems require comprehensive error handling, scalability considerations, and proper documentation to ensure long-term maintainability and reliability.\"\n ],\n [\n 'question' => \"When implementing {$title}, what is the most critical factor to consider first?\",\n 'options' => [\n \"Code aesthetics and formatting\",\n \"System architecture and design patterns\",\n \"Using the latest trending libraries\",\n \"Writing code as quickly as possible\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"System architecture and design patterns should be considered first as they form the foundation that affects all subsequent implementation decisions and long-term maintainability.\"\n ],\n [\n 'question' => \"In the context of {$title}, how should you handle performance optimization?\",\n 'options' => [\n \"Optimize everything from the start even without bottlenecks\",\n \"Profile first, identify bottlenecks, then optimize strategically\",\n \"Never optimize, it's premature optimization\",\n \"Only optimize when users complain\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"The best practice is to profile first to identify actual bottlenecks, then optimize strategically based on data. This prevents wasted effort on non-issues while addressing real performance problems.\"\n ],\n [\n 'question' => \"What testing strategy is most appropriate for {$title}?\",\n 'options' => [\n \"Only manual testing when features are complete\",\n \"Comprehensive unit, integration, and end-to-end testing\",\n \"No testing, just deploy and fix bugs later\",\n \"Only test the happy path scenarios\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"A comprehensive testing strategy with unit tests, integration tests, and end-to-end tests provides the best coverage and catches issues at different levels, reducing bugs in production.\"\n ],\n [\n 'question' => \"When maintaining code related to {$title}, what principle should guide your decisions?\",\n 'options' => [\n \"Always rewrite everything with new technologies\",\n \"Balance between technical debt, business needs, and code quality\",\n \"Never change working code regardless of quality\",\n \"Prioritize speed over all other considerations\"\n ],\n 'correct_answer' => 1,\n 'explanation' => \"Effective code maintenance requires balancing technical debt management with business requirements and code quality. This pragmatic approach ensures sustainable development while meeting business objectives.\"\n ]\n ];\n }\n}\n"}}}} |