module.exports=[93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},63021,(e,t,r)=>{t.exports=e.x("@prisma/client-2c3a283f134fdcb6",()=>require("@prisma/client-2c3a283f134fdcb6"))},18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},70406,(e,t,r)=>{t.exports=e.x("next/dist/compiled/@opentelemetry/api",()=>require("next/dist/compiled/@opentelemetry/api"))},43793,e=>{"use strict";var t=e.i(63021);let r=globalThis.prisma??new t.PrismaClient({log:["query"]});e.s(["db",0,r])},36162,e=>{"use strict";let t={baseUrl:process.env.OLLAMA_BASE_URL||"http://localhost:11434",defaultModel:process.env.OLLAMA_MODEL||"granite3.1-moe",fallbackModel:"llama3.2",maxTokens:2048,temperature:.7};function r(){return t.baseUrl.replace(/\/$/,"")}async function a(e,n,s){let o=r(),i=n||t.defaultModel;try{let r=await fetch(`${o}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:i,messages:e,stream:!1,options:{temperature:s?.temperature??t.temperature,num_predict:s?.maxTokens??t.maxTokens,top_p:s?.topP,frequency_penalty:s?.frequencyPenalty,presence_penalty:s?.presencePenalty}})});if(!r.ok)throw Error(`Ollama API error: ${r.status} ${r.statusText}`);return(await r.json()).response}catch(r){if(!n&&t.fallbackModel)return console.warn(`Model ${i} failed, trying fallback ${t.fallbackModel}:`,r instanceof Error?r.message:r),a(e,t.fallbackModel,s);throw r}}async function n(e){let t=r(),a=await fetch(`${t}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:"nomic-embed-text",prompt:e})});if(!a.ok)throw Error(`Embedding API error: ${a.status} ${a.statusText}`);return(await a.json()).embedding}async function s(){let e=r(),t=await fetch(`${e}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw Error(`Failed to list models: ${t.status}`);return(await t.json()).models||[]}async function o(){try{let e=r(),t=new AbortController,a=setTimeout(()=>t.abort(),5e3),n=await fetch(`${e}/api/tags`,{method:"GET",signal:t.signal});return clearTimeout(a),n.ok}catch{return!1}}async function i(e,a,n,s){let o=r(),l=n||t.defaultModel,c="";try{let r=await fetch(`${o}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:l,messages:e,stream:!0,options:{temperature:s?.temperature??t.temperature,num_predict:s?.maxTokens??t.maxTokens}})});if(!r.ok||!r.body)throw Error(`Ollama streaming error: ${r.status}`);let n=r.body.getReader(),i=new TextDecoder;for(;;){let{done:e,value:t}=await n.read();if(e)break;for(let e of i.decode(t,{stream:!0}).split("\n").filter(Boolean))try{let t=JSON.parse(e);if(t.response&&(c+=t.response,a(t.response)),t.done)break}catch{}}return c}catch(r){if(!n&&t.fallbackModel)return console.warn(`Stream model ${l} failed, trying fallback ${t.fallbackModel}`),i(e,a,t.fallbackModel,s);throw r}}async function l(e,t,r){let n=[];return r&&n.push({role:"system",content:r}),n.push({role:"user",content:e}),a(n,t)}e.s(["chatCompletion",()=>a,"generate",()=>l,"generateEmbedding",()=>n,"isHealthy",()=>o,"listModels",()=>s,"streamChat",()=>i],36162)},23316,e=>{"use strict";var t=e.i(47909),r=e.i(74017),a=e.i(96250),n=e.i(59756),s=e.i(61916),o=e.i(74677),i=e.i(69741),l=e.i(16795),c=e.i(87718),d=e.i(95169),u=e.i(47587),p=e.i(66012),h=e.i(70101),m=e.i(26937),f=e.i(10372),g=e.i(93695);e.i(52474);var y=e.i(220),x=e.i(89171),w=e.i(36162),b=e.i(43793);let v=`You are Studo-Guide AI, an intelligent career guidance and academic support assistant for South African students. You help learners from Grade 8 to post-matric with:
- Career guidance and subject selection
- Study tips and exam preparation (CAPS curriculum)
- Bursary and scholarship information
- University application guidance (SA universities)
- APS score calculation and advice
- Motivation and academic planning
- Tutor subject recommendations

You are knowledgeable about the South African education system including:
- All 9 provinces and their schools/universities
- CAPS curriculum subjects and requirements
- SA university admission requirements
- NSFAS and other bursary schemes
- SA career market trends

Always be encouraging, supportive, and practical. Use South African English conventions.`;async function R(){try{let e=await (0,w.isHealthy)();return x.NextResponse.json({status:e?"online":"offline"},{status:200})}catch{return x.NextResponse.json({status:"offline"},{status:503})}}async function E(e){try{let t,{messages:r,userId:a}=await e.json();if(!r||!Array.isArray(r)||0===r.length)return x.NextResponse.json({error:"Please provide at least one message."},{status:400});let n=[{role:"system",content:v},...r.map(e=>({role:"user"===e.role?"user":"assistant"===e.role?"assistant":"user",content:e.content}))];try{t=await (0,w.chatCompletion)(n)}catch(e){return console.error("Ollama call failed:",e instanceof Error?e.message:e),x.NextResponse.json({error:"The AI model is currently unavailable. It may be starting up — please try again in a moment."},{status:503})}let s=Math.ceil(t.length/4)+Math.ceil(r.reduce((e,t)=>e+t.content.length,0)/4),o=r[r.length-1];if(o&&"user"===o.role)try{await b.db.chatMessage.create({data:{userId:a||"anonymous",role:"user",content:o.content,model:"granite3.1-moe",tokensUsed:Math.ceil(o.content.length/4)}})}catch{}try{await b.db.chatMessage.create({data:{userId:a||"anonymous",role:"assistant",content:t,model:"granite3.1-moe",tokensUsed:s}})}catch{}return x.NextResponse.json({response:t,tokensUsed:s})}catch(e){return console.error("Chat API error:",e instanceof Error?e.message:e),x.NextResponse.json({error:"An internal error occurred. Please try again."},{status:500})}}e.s(["OPTIONS",()=>R,"POST",()=>E],74441);var A=e.i(74441);let C=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/ai/chat/route",pathname:"/api/ai/chat",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/ai/chat/route.ts",nextConfigOutput:"standalone",userland:A}),{workAsyncStorage:T,workUnitAsyncStorage:k,serverHooks:S}=C;function P(){return(0,a.patchFetch)({workAsyncStorage:T,workUnitAsyncStorage:k})}async function O(e,t,a){C.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let x="/api/ai/chat/route";x=x.replace(/\/index$/,"")||"/";let w=await C.prepare(e,t,{srcPage:x,multiZoneDraftMode:!1});if(!w)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:b,params:v,nextConfig:R,parsedUrl:E,isDraftMode:A,prerenderManifest:T,routerServerContext:k,isOnDemandRevalidate:S,revalidateOnlyGenerated:P,resolvedPathname:O,clientReferenceManifest:N,serverActionsManifest:j}=w,M=(0,i.normalizeAppPath)(x),_=!!(T.dynamicRoutes[M]||T.routes[O]),q=async()=>((null==k?void 0:k.render404)?await k.render404(e,t,E,!1):t.end("This page could not be found"),null);if(_&&!A){let e=!!T.routes[O],t=T.dynamicRoutes[M];if(t&&!1===t.fallback&&!e){if(R.experimental.adapterPath)return await q();throw new g.NoFallbackError}}let $=null;!_||C.isDev||A||($="/index"===($=O)?"/":$);let I=!0===C.isDev||!_,U=_&&!I;j&&N&&(0,o.setManifestsSingleton)({page:x,clientReferenceManifest:N,serverActionsManifest:j});let H=e.method||"GET",D=(0,s.getTracer)(),L=D.getActiveScopeSpan(),F={params:v,prerenderManifest:T,renderOpts:{experimental:{authInterrupts:!!R.experimental.authInterrupts},cacheComponents:!!R.cacheComponents,supportsDynamicResponse:I,incrementalCache:(0,n.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:R.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>C.onRequestError(e,t,a,n,k)},sharedContext:{buildId:b}},B=new l.NodeNextRequest(e),K=new l.NodeNextResponse(t),G=c.NextRequestAdapter.fromNodeNextRequest(B,(0,c.signalFromNodeResponse)(t));try{let o=async e=>C.handle(G,F).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=D.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${H} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t)}else e.updateName(`${H} ${x}`)}),i=!!(0,n.getRequestMeta)(e,"minimalMode"),l=async n=>{var s,l;let c=async({previousCacheEntry:r})=>{try{if(!i&&S&&P&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await o(n);e.fetchMetrics=F.renderOpts.fetchMetrics;let l=F.renderOpts.pendingWaitUntil;l&&a.waitUntil&&(a.waitUntil(l),l=void 0);let c=F.renderOpts.collectedTags;if(!_)return await (0,p.sendResponse)(B,K,s,F.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(s.headers);c&&(t[f.NEXT_CACHE_TAGS_HEADER]=c),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==F.renderOpts.collectedRevalidate&&!(F.renderOpts.collectedRevalidate>=f.INFINITE_CACHE)&&F.renderOpts.collectedRevalidate,a=void 0===F.renderOpts.collectedExpire||F.renderOpts.collectedExpire>=f.INFINITE_CACHE?void 0:F.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await C.onRequestError(e,t,{routerKind:"App Router",routePath:x,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:S})},!1,k),t}},d=await C.handleResponse({req:e,nextConfig:R,cacheKey:$,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:T,isRoutePPREnabled:!1,isOnDemandRevalidate:S,revalidateOnlyGenerated:P,responseGenerator:c,waitUntil:a.waitUntil,isMinimalMode:i});if(!_)return null;if((null==d||null==(s=d.value)?void 0:s.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(l=d.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});i||t.setHeader("x-nextjs-cache",S?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let g=(0,h.fromNodeOutgoingHttpHeaders)(d.value.headers);return i&&_||g.delete(f.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||g.get("Cache-Control")||g.set("Cache-Control",(0,m.getCacheControlHeader)(d.cacheControl)),await (0,p.sendResponse)(B,K,new Response(d.value.body,{headers:g,status:d.value.status||200})),null};L?await l(L):await D.withPropagatedContext(e.headers,()=>D.trace(d.BaseServerSpan.handleRequest,{spanName:`${H} ${x}`,kind:s.SpanKind.SERVER,attributes:{"http.method":H,"http.target":e.url}},l))}catch(t){if(t instanceof g.NoFallbackError||await C.onRequestError(e,t,{routerKind:"App Router",routePath:M,routeType:"route",revalidateReason:(0,u.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:S})},!1,k),_)throw t;return await (0,p.sendResponse)(B,K,new Response(null,{status:500})),null}}e.s(["handler",()=>O,"patchFetch",()=>P,"routeModule",()=>C,"serverHooks",()=>S,"workAsyncStorage",()=>T,"workUnitAsyncStorage",()=>k],23316)}];

//# sourceMappingURL=%5Broot-of-the-server%5D__bdac874a._.js.map