#!/usr/bin/env node
import'./chunk-5TAVYPOV.js';import h,{Router}from'express';import*as u from'path';import*as a from'fs';import {fileURLToPath}from'url';import d from'chalk';function N(n){let r=Router();return r.get("/",(o,s)=>{let e=u.join(n,"courses");if(!a.existsSync(e))return s.json({courses:[]});let i=a.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>{let l=JSON.parse(a.readFileSync(u.join(e,t),"utf-8"));return {id:l.id,title:l.title,description:l.description,lessonCount:l.lessons?.length||0,lessons:(l.lessons||[]).map(c=>({id:c.id,title:c.title}))}});return i.sort((t,l)=>t.id.localeCompare(l.id)),s.json({courses:i})}),r.get("/:id",(o,s)=>{let e=u.join(n,"courses",`${o.params.id}.json`);if(!a.existsSync(e))return s.status(404).json({error:`Course '${o.params.id}' not found`});let i=JSON.parse(a.readFileSync(e,"utf-8"));return s.json(i)}),r.get("/:id/lessons/:lessonId",(o,s)=>{let e=u.join(n,"courses",`${o.params.id}.json`);if(!a.existsSync(e))return s.status(404).json({error:`Course '${o.params.id}' not found`});let i=(JSON.parse(a.readFileSync(e,"utf-8")).lessons||[]).find(t=>t.id===o.params.lessonId);return i?s.json(i):s.status(404).json({error:`Lesson '${o.params.lessonId}' not found`})}),r}function v(n){return n[Math.floor(Math.random()*n.length)]}function F(n){for(let r=n.length-1;r>0;r--){let o=Math.floor(Math.random()*(r+1));[n[r],n[o]]=[n[o],n[r]];}return n}function L(n){let r={},o=[];for(let s of n.items)if(s.type==="standalone"||s.type==="variant-group"){let e=v(s.variants);o.push([{id:e.id,course:s.course,scenario:e.scenario,question:e.question,choices:e.choices,correct:e.correct,explanation:e.explanation}]);}else {r[s.slot]=s.passage;let e=s.questions.map(i=>{let t=v(i.variants);return {id:t.id,course:s.course,scenario:t.scenario,question:t.question,choices:t.choices,correct:t.correct,explanation:t.explanation,passageId:s.slot}});o.push(e);}return F(o),{questions:o.flat(),passages:r}}function J(n){let r=0;for(let o of n.items)o.type==="standalone"||o.type==="variant-group"?r+=1:r+=o.questions.length;return r}function k(n,r){let o=Router();return o.get("/",(s,e)=>{let i=u.join(n,"plsat");if(!a.existsSync(i))return e.json({versions:[]});let t=a.readdirSync(i).filter(l=>l.endsWith(".json")).map(l=>{let c=JSON.parse(a.readFileSync(u.join(i,l),"utf-8")),p=c.items?J(c):c.questions?.length||0;return {version:c.version,frameworkVersion:c.frameworkVersion,questionCount:p,timeLimit:c.timeLimit,passThreshold:c.passThreshold}});return t.sort((l,c)=>c.version.localeCompare(l.version)),e.json({versions:t})}),o.get("/:version",(s,e)=>{try{let i=u.join(n,"plsat",`v${s.params.version}.json`);if(!a.existsSync(i))return e.status(404).json({error:`PLSAT version '${s.params.version}' not found`});let t=JSON.parse(a.readFileSync(i,"utf-8"));if(t.items){let{questions:c,passages:p}=L(t);return e.json({version:t.version,frameworkVersion:t.frameworkVersion,timeLimit:t.timeLimit,passThreshold:t.passThreshold,title:t.title,description:t.description,questions:c,...Object.keys(p).length>0?{passages:p}:{}})}let l=[...t.questions].sort(()=>Math.random()-.5);return e.json({...t,questions:l})}catch(i){let t=i instanceof Error?i.message:"Internal error";return e.status(500).json({error:`Failed to load PLSAT exam: ${t}`})}}),o.post("/diploma",(s,e)=>{if(!r)return e.status(400).json({error:"No project directory configured"});let i=u.join(r,".paradigm","university","diplomas");if(!a.existsSync(i))return e.json({saved:false,reason:"university directory not found"});try{let{student:t,version:l,score:c,total:p,percentage:O,passed:x}=s.body;if(!t||!l||c==null||p==null)return e.status(400).json({error:"Missing required fields: student, version, score, total"});let w=new Date().toISOString().slice(0,10),$=String(t).toLowerCase().replace(/[^a-z0-9-]/g,"-").slice(0,20),j=`D-${w}-${$}-plsat-v${l}`,P={id:j,type:"plsat",student:$,earnedAt:new Date().toISOString(),source:`plsat:v${l}`,score:c,total:p,percentage:O??(p>0?Math.round(c/p*1e4)/100:0),passed:x??!1,details:{plsatVersion:l}},b=u.join(i,`${j}.yaml`),q=Object.entries(P).map(([g,f])=>{if(typeof f=="object"&&f!==null){let A=Object.entries(f).map(([C,I])=>`  ${C}: ${JSON.stringify(I)}`).join(`
`);return `${g}:
${A}`}return `${g}: ${JSON.stringify(f)}`});return a.writeFileSync(b,q.join(`
`)+`
`,"utf8"),e.json({saved:!0,diplomaId:j})}catch(t){let l=t instanceof Error?t.message:"Internal error";return e.status(500).json({error:`Failed to save diploma: ${l}`})}}),o}var M=fileURLToPath(import.meta.url),y=u.dirname(M);function E(n){let r=n;for(;r!==u.dirname(r);){if(a.existsSync(u.join(r,"package.json"))&&JSON.parse(a.readFileSync(u.join(r,"package.json"),"utf-8")).name==="@a-company/university")return r;r=u.dirname(r);}return n}var m={component(n){let r=d.magenta(`#${n}`);return {info:(o,s)=>{let e=s?d.gray(` ${Object.entries(s).map(([i,t])=>`${i}=${t}`).join(" ")}`):"";console.log(`${d.blue("\u2139")} ${r} ${o}${e}`);},success:(o,s)=>{let e=s?d.gray(` ${Object.entries(s).map(([i,t])=>`${i}=${t}`).join(" ")}`):"";console.log(`${d.green("\u2714")} ${r} ${o}${e}`);},warn:(o,s)=>{let e=s?d.gray(` ${Object.entries(s).map(([i,t])=>`${i}=${t}`).join(" ")}`):"";console.log(`${d.yellow("\u26A0")} ${r} ${o}${e}`);},error:(o,s)=>{let e=s?d.gray(` ${Object.entries(s).map(([i,t])=>`${i}=${t}`).join(" ")}`):"";console.error(`${d.red("\u2716")} ${r} ${o}${e}`);}}}};function V(n){if(n?.contentDir&&n?.uiDistPath)return {contentDir:n.contentDir,uiDistPath:n.uiDistPath};let r=u.join(y,"university-content"),o=u.join(y,"university-ui");if(a.existsSync(r)&&a.existsSync(o))return {contentDir:n?.contentDir||r,uiDistPath:n?.uiDistPath||o};let s=E(y);return {contentDir:n?.contentDir||u.join(s,"src","content"),uiDistPath:n?.uiDistPath||u.join(s,"ui","dist")}}function D(n){let r=h();r.use(h.json()),r.use((e,i,t)=>{i.header("Access-Control-Allow-Origin","*"),i.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.header("Access-Control-Allow-Headers","Content-Type"),t();});let{contentDir:o,uiDistPath:s}=V(n);return r.use("/api/courses",N(o)),r.use("/api/plsat",k(o,n?.projectDir)),r.get("/api/reference",(e,i)=>{let t=u.join(o,"reference.json");if(a.existsSync(t)){let l=JSON.parse(a.readFileSync(t,"utf-8"));i.json(l);}else i.status(404).json({error:"Reference data not found"});}),r.get("/api/health",(e,i)=>{i.json({status:"ok",timestamp:new Date().toISOString()});}),a.existsSync(s)&&(r.use(h.static(s)),r.get("{*path}",(e,i)=>{e.path.startsWith("/api")||i.sendFile(u.join(s,"index.html"));})),r}async function R(n){let r=D({contentDir:n.contentDir,uiDistPath:n.uiDistPath,projectDir:n.projectDir});return m.component("university-server").info("Starting server",{port:n.port}),new Promise((o,s)=>{r.listen(n.port,()=>{m.component("university-server").success("Server running",{url:`http://localhost:${n.port}`}),n.open&&import('open').then(e=>{e.default(`http://localhost:${n.port}`),m.component("university-server").info("Opened browser");}).catch(()=>{m.component("university-server").warn("Could not open browser automatically");}),o();}).on("error",e=>{e.code==="EADDRINUSE"?m.component("university-server").error("Port already in use",{port:n.port}):m.component("university-server").error("Server error",{error:e.message}),s(e);});})}
export{D as createApp,R as startServer};