module.exports=[522734,(e,t,n)=>{t.exports=e.x("fs",()=>require("fs"))},363485,e=>{"use strict";var t=e.i(747909),n=e.i(174017),r=e.i(996250),a=e.i(759756),s=e.i(561916),o=e.i(174677),i=e.i(869741),l=e.i(316795),u=e.i(487718),c=e.i(995169),d=e.i(47587),p=e.i(666012),g=e.i(570101),h=e.i(626937),f=e.i(10372),m=e.i(193695);e.i(52474);var w=e.i(600220),R=e.i(522734),y=e.i(814747),v=e.i(89171);let x=process.env.GEMINI_EMBEDDING_MODEL||"gemini-embedding-001",E=(process.env.GEMINI_GENERATION_MODELS||"gemini-2.5-flash,gemini-flash-lite-latest,gemini-2.0-flash").split(",").map(e=>e.trim()).filter(Boolean),b=y.default.join(process.cwd(),"data","faq_index.json"),C="اكتب سؤالك من فضلك.",N="حاليًا لا أجد إجابة مباشرة لهذا السؤال ضمن بيانات الموقع المتاحة لدي.",A="حدث خلل مؤقت. حاول مرة أخرى بعد قليل.",T=new Map,S=new Map;function _(e){return e.normalize("NFKC").replace(/[\u064B-\u0652\u0670]/g,"").replace(/[أإآ]/g,"ا").replace(/ة/g,"ه").replace(/ى/g,"ي").replace(/ـ+/g,"").replace(/[^\p{L}\p{N}\s]/gu," ").toLowerCase().replace(/\s+/g," ").trim()}function $(e){let t=e;for(let[e,n]of[[/\bفين\b/gi,"اين"],[/\bوين\b/gi,"اين"],[/\bايش\b/gi,"ما"],[/\bاش\b/gi,"ما"],[/\bشلون\b/gi,"كيف"],[/\bقديش\b/gi,"كم"]])t=t.replace(e,n);return _(t)}function k(e,t){return t.some(t=>e.includes(t))}async function M(e,t,n=2){let r=null;for(let a=0;a<=n;a+=1){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(s.ok)return{status:s.status,data:await s.json()};let o=await s.text();if(r={status:s.status,message:o},!(429===s.status||s.status>=500)||a===n)break;await function(e){return new Promise(t=>setTimeout(t,e))}(1200*(a+1))}return{status:r?.status||500,data:null,errorText:r?.message||"Unknown error"}}async function O(e,t){let n=`https://generativelanguage.googleapis.com/v1beta/models/${x}:embedContent?key=${encodeURIComponent(e)}`,r=await M(n,{content:{parts:[{text:t}]}});if(!r.data)throw Error(`Gemini embedding request failed (${r.status}): ${r.errorText}`);let a=r.data?.embedding?.values;if(!Array.isArray(a)||0===a.length)throw Error("Gemini embedding response is invalid.");return a}async function j(e,t,n){let r=`https://generativelanguage.googleapis.com/v1beta/models/${t}:generateContent?key=${encodeURIComponent(e)}`,a=await M(r,{contents:[{role:"user",parts:[{text:n}]}],generationConfig:{temperature:.25}});return a.data?{ok:!0,text:a.data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim()||""}:{ok:!1,status:a.status,errorText:a.errorText}}async function q(e,t,n){let r=n.map((e,t)=>`Q${t+1}: ${e.question}
A${t+1}: ${e.answer}`).join("\n\n"),a=`أنت مساعد رسمي لجامعة الجيل الجديد.
التعليمات:
- أجب باللغة العربية بأسلوب مهذب ومنظم ومختصر.
- أجب فقط من "المصدر".
- لا تضف أي معلومة غير موجودة في المصدر.
- إذا كانت الإجابة غير متوفرة بوضوح من المصدر، أعد هذه الجملة فقط: ${N}
- إذا كانت المعلومة غير مؤكدة، استخدم صياغة عامة بدون أرقام أو حقائق جديدة.

السؤال:
${t}

المصدر:
${r}`,s="";for(let t of E){let n=await j(e,t,a);if(n.ok&&n.text)return{answer:n.text,usedModel:t};s=`model=${t} status=${n.status} error=${n.errorText}`}return console.error(`Gemini generation failed on all models. ${s}`),{answer:N,usedModel:"fallback"}}async function P(e){let t=Date.now(),n="none",r=0,a=0;try{var s;let o,i,l;if(s=function(e){let t=e.headers.get("x-forwarded-for");if(t)return t.split(",")[0]?.trim()||"unknown";let n=e.headers.get("x-real-ip");return n?n.trim():"unknown"}(e),o=Date.now(),(i=(T.get(s)||[]).filter(e=>o-e<6e4)).length>=10?(T.set(s,i),!0):(i.push(o),T.set(s,i),!1))return v.NextResponse.json({answer:"الرجاء الانتظار قليلًا قبل إرسال سؤال جديد.",suggestions:[]});let u={};try{u=await e.json()}catch{return v.NextResponse.json({answer:C,type:"small_talk",suggestions:[]})}let c=("string"==typeof u?.question?u.question:"").trim(),d=$(c);if(console.log("[smartchat] question:",c),!c)return v.NextResponse.json({answer:C,type:"small_talk",suggestions:[]});let p=S.get(d);if(p&&p.expiresAt>Date.now())return n="cache",console.log("[smartchat] usedLLM:",n),console.log("[smartchat] responseTime:",`${Date.now()-t}ms`),v.NextResponse.json({answer:p.answer,type:"university",suggestions:p.suggestions});let g=(l=$(c),k(l,["السلام عليكم","السلام","مرحبا","اهلا","ما اسمك","من انت","مين انت","كيف استخدم الشات","ساعدني"])||/(hi|hello|your name|who are you|help)/i.test(l)?"small_talk":k(l,["جامعه","الجامعه","الجيل الجديد","قبول","تسجيل","رسوم","منح","كليه","الكليات","برنامج","برامج","تخصص","الموقع","العنوان","تواصل","البريد","الهاتف","شؤون الطلاب","الدوام","المواعيد","اين","وين","فين"])||/(aau|admission|registration|tuition|college|program|university|campus)/i.test(l)?"university":"outside");if("small_talk"===g){let e;return v.NextResponse.json({answer:(e=$(c),k(e,["السلام عليكم","السلام","مرحبا","اهلا"])||/(hi|hello)/i.test(e)?"وعليكم السلام! أنا مساعد الموقع. اسمي اسألني عن الجامعة وسأجيبك من معلومات الموقع.":k(e,["ما اسمك","من انت","مين انت"])||/(your name|who are you)/i.test(e)?"أنا مساعد جامعة الجيل الجديد اسمي AAU.":k(e,["كيف استخدم الشات","ساعدني"])||/(help)/i.test(e)?"اكتب سؤالك عن القبول، الكليات، البرامج، الرسوم، الموقع... وسأساعدك.":k(e,["كيف حالك","اخبارك"])||/(how are you)/i.test(e)?"أنا بخير، شكرًا لك. أنا هنا لمساعدتك فيما يخص جامعة الجيل الجديد.":"مرحبًا بك! اسألني أي سؤال يتعلق بجامعة الجيل الجديد."),type:g,suggestions:[]})}if("outside"===g)return v.NextResponse.json({answer:"أعتذر، أنا مساعد مخصص لأسئلة جامعة الجيل الجديد فقط. اسألني عن القبول، الكليات، البرامج، الرسوم، أو خدمات الجامعة.",type:g,suggestions:[]});let h=process.env.GEMINI_API_KEY;if(!h)return v.NextResponse.json({answer:A,type:"university",suggestions:[]});let f=function(){if(!R.default.existsSync(b))throw Error("data/faq_index.json not found.");let e=JSON.parse(R.default.readFileSync(b,"utf8"));if(!Array.isArray(e.items)||0===e.items.length)throw Error("data/faq_index.json is empty or invalid.");return e}(),m=d||c,w=await O(h,m),y=function(e,t,n,r=4){return n.map(n=>{let r=function(e,t){let n=0,r=0,a=0,s=Math.min(e.length,t.length);for(let o=0;o<s;o+=1)n+=e[o]*t[o],r+=e[o]*e[o],a+=t[o]*t[o];return 0===r||0===a?0:n/(Math.sqrt(r)*Math.sqrt(a))}(e,n.embedding),a=function(e,t){let n=e.split(" ").filter(Boolean);if(0===n.length)return 0;let r=new Set(t.split(" ").filter(Boolean)),a=0;for(let e of n)r.has(e)&&(a+=1);return a/n.length}(t,_(n.question));return{...n,semanticScore:r,keywordScore:a,finalScore:.8*r+.2*a}}).sort((e,t)=>t.finalScore-e.finalScore).slice(0,r)}(w,d,f.items,4),x=y[0]?.finalScore??0;r=y[0]?.semanticScore??0,a=x;let E=y.slice(0,3).map(e=>e.question);if(console.log("[smartchat] semanticScore:",r),console.log("[smartchat] finalScore:",a),x<.35)return v.NextResponse.json({answer:function(e){let t=[`${N} لأساعدك بشكل أدق، هل تقصد:`,"- القبول والتسجيل؟","- الرسوم والمنح؟","- البرامج/التخصصات؟","- التواصل والعنوان؟","اكتب اسم الكلية/البرنامج أو أي تفاصيل إضافية وسأوجهك لأقرب معلومات متاحة."];if(e.length>0)for(let n of(t.push("قد تفيدك هذه الأسئلة القريبة:"),e))t.push(`- ${n}`);return t.join("\n")}(E),type:"university",suggestions:E});let M=await q(h,c,y);n=M.usedModel;let j=M.answer||N;return S.set(d,{answer:j,suggestions:E,expiresAt:Date.now()+3e5}),console.log("[smartchat] usedLLM:",n),console.log("[smartchat] responseTime:",`${Date.now()-t}ms`),v.NextResponse.json({answer:j,type:"university",suggestions:E})}catch(e){return console.error("smartchat api error:",e instanceof Error?e.message:"Unknown server error."),v.NextResponse.json({answer:A,type:"university",suggestions:[]})}finally{0===r&&console.log("[smartchat] semanticScore:",r),0===a&&console.log("[smartchat] finalScore:",a),"none"===n&&console.log("[smartchat] usedLLM:",n),console.log("[smartchat] responseTime:",`${Date.now()-t}ms`)}}e.s(["POST",()=>P,"runtime",0,"nodejs"],572723);var I=e.i(572723);let D=new t.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/smartchat/route",pathname:"/api/smartchat",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/smartchat/route.ts",nextConfigOutput:"",userland:I}),{workAsyncStorage:U,workUnitAsyncStorage:H,serverHooks:L}=D;function G(){return(0,r.patchFetch)({workAsyncStorage:U,workUnitAsyncStorage:H})}async function B(e,t,r){D.isDev&&(0,a.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let R="/api/smartchat/route";R=R.replace(/\/index$/,"")||"/";let y=await D.prepare(e,t,{srcPage:R,multiZoneDraftMode:!1});if(!y)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:v,params:x,nextConfig:E,parsedUrl:b,isDraftMode:C,prerenderManifest:N,routerServerContext:A,isOnDemandRevalidate:T,revalidateOnlyGenerated:S,resolvedPathname:_,clientReferenceManifest:$,serverActionsManifest:k}=y,M=(0,i.normalizeAppPath)(R),O=!!(N.dynamicRoutes[M]||N.routes[_]),j=async()=>((null==A?void 0:A.render404)?await A.render404(e,t,b,!1):t.end("This page could not be found"),null);if(O&&!C){let e=!!N.routes[_],t=N.dynamicRoutes[M];if(t&&!1===t.fallback&&!e){if(E.experimental.adapterPath)return await j();throw new m.NoFallbackError}}let q=null;!O||D.isDev||C||(q="/index"===(q=_)?"/":q);let P=!0===D.isDev||!O,I=O&&!P;k&&$&&(0,o.setManifestsSingleton)({page:R,clientReferenceManifest:$,serverActionsManifest:k});let U=e.method||"GET",H=(0,s.getTracer)(),L=H.getActiveScopeSpan(),G={params:x,prerenderManifest:N,renderOpts:{experimental:{authInterrupts:!!E.experimental.authInterrupts},cacheComponents:!!E.cacheComponents,supportsDynamicResponse:P,incrementalCache:(0,a.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:E.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,n,r,a)=>D.onRequestError(e,t,r,a,A)},sharedContext:{buildId:v}},B=new l.NodeNextRequest(e),F=new l.NodeNextResponse(t),K=u.NextRequestAdapter.fromNodeNextRequest(B,(0,u.signalFromNodeResponse)(t));try{let o=async e=>D.handle(K,G).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let n=H.getRootSpanAttributes();if(!n)return;if(n.get("next.span_type")!==c.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${n.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let r=n.get("next.route");if(r){let t=`${U} ${r}`;e.setAttributes({"next.route":r,"http.route":r,"next.span_name":t}),e.updateName(t)}else e.updateName(`${U} ${R}`)}),i=!!(0,a.getRequestMeta)(e,"minimalMode"),l=async a=>{var s,l;let u=async({previousCacheEntry:n})=>{try{if(!i&&T&&S&&!n)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await o(a);e.fetchMetrics=G.renderOpts.fetchMetrics;let l=G.renderOpts.pendingWaitUntil;l&&r.waitUntil&&(r.waitUntil(l),l=void 0);let u=G.renderOpts.collectedTags;if(!O)return await (0,p.sendResponse)(B,F,s,G.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,g.toNodeOutgoingHttpHeaders)(s.headers);u&&(t[f.NEXT_CACHE_TAGS_HEADER]=u),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let n=void 0!==G.renderOpts.collectedRevalidate&&!(G.renderOpts.collectedRevalidate>=f.INFINITE_CACHE)&&G.renderOpts.collectedRevalidate,r=void 0===G.renderOpts.collectedExpire||G.renderOpts.collectedExpire>=f.INFINITE_CACHE?void 0:G.renderOpts.collectedExpire;return{value:{kind:w.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:n,expire:r}}}}catch(t){throw(null==n?void 0:n.isStale)&&await D.onRequestError(e,t,{routerKind:"App Router",routePath:R,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isStaticGeneration:I,isOnDemandRevalidate:T})},!1,A),t}},c=await D.handleResponse({req:e,nextConfig:E,cacheKey:q,routeKind:n.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:N,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:S,responseGenerator:u,waitUntil:r.waitUntil,isMinimalMode:i});if(!O)return null;if((null==c||null==(s=c.value)?void 0:s.kind)!==w.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(l=c.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});i||t.setHeader("x-nextjs-cache",T?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),C&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,g.fromNodeOutgoingHttpHeaders)(c.value.headers);return i&&O||m.delete(f.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,h.getCacheControlHeader)(c.cacheControl)),await (0,p.sendResponse)(B,F,new Response(c.value.body,{headers:m,status:c.value.status||200})),null};L?await l(L):await H.withPropagatedContext(e.headers,()=>H.trace(c.BaseServerSpan.handleRequest,{spanName:`${U} ${R}`,kind:s.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},l))}catch(t){if(t instanceof m.NoFallbackError||await D.onRequestError(e,t,{routerKind:"App Router",routePath:M,routeType:"route",revalidateReason:(0,d.getRevalidateReason)({isStaticGeneration:I,isOnDemandRevalidate:T})},!1,A),O)throw t;return await (0,p.sendResponse)(B,F,new Response(null,{status:500})),null}}e.s(["handler",()=>B,"patchFetch",()=>G,"routeModule",()=>D,"serverHooks",()=>L,"workAsyncStorage",()=>U,"workUnitAsyncStorage",()=>H],363485)}];

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