import{createServer}from"http";import{EventEmitter}from"events";import{readdirSync,existsSync,mkdirSync,writeFileSync,appendFileSync,statSync,createReadStream}from"fs";import{join,extname}from"path";import{fileURLToPath}from"url";import{dirname}from"path";const __filename=fileURLToPath(import.meta.url),__dirname=dirname(__filename),LOG_FILE=join(process.cwd(),"logs","server.log"),STATIC_FOLDER=join(process.cwd(),"public");class ZingJS{constructor({enableCors:e=!1,enableRateLimit:t=!1,enableLogging:s=!0,serveStatic:r=!1,defaultResponseType:i="json",enableDocs:o=!1}={}){this.server=createServer(this.requestHandler.bind(this)),this.middlewares=[],this.eventBus=new EventEmitter,this.routes={},this.dynamicRoutes=[],this.enableLogging=s,this.serveStatic=r,this.defaultResponseType=i,this.enableDocs=o,this.ensureRoutesFolder(),r&&this.ensureStaticFolder(),s&&this.setupLogging(),this.loadRoutes(),this.setupDefaultRoutes(),this.use(this.jsonParserMiddleware),e&&this.use(this.corsMiddleware),t&&this.use(this.rateLimitMiddleware())}use(e){this.middlewares.push(e)}on(e,t){this.eventBus.on(e,t)}emit(e,t){this.eventBus.emit(e,t)}generateDocs(){return{info:{title:"ZingJS API",version:"1.0.0",description:"Auto-generated API documentation for ZingJS"},paths:Object.keys(this.routes).reduce(((e,t)=>{const[s,r]=t.split(":");return e[s]||(e[s]={}),e[s][r.toLowerCase()]={description:`Handler for ${r} ${s}`,responses:{200:{description:"Successful response"}}},e}),{})}}ensureRoutesFolder(){const e=join(process.cwd(),"routes");existsSync(e)||(mkdirSync(e,{recursive:!0}),writeFileSync(join(e,"index.js"),"export default { GET: (req) => ({ message: 'Hello from ZingJS dynamic route!' }) };\n"))}ensureStaticFolder(){existsSync(STATIC_FOLDER)||mkdirSync(STATIC_FOLDER,{recursive:!0})}setupLogging(){const e=join(process.cwd(),"logs");existsSync(e)||mkdirSync(e,{recursive:!0}),this.log("[INFO] Logging initialized")}log(e){if(!this.enableLogging)return;const t=`[${(new Date).toISOString()}] ${e}\n`;console.log(t.trim()),appendFileSync(LOG_FILE,t)}async loadRoutes(){const e=join(process.cwd(),"routes");if(existsSync(e)){const t=async(e,t)=>{try{const s=await import(e);t.includes("[")?this.dynamicRoutes.push({routePath:t,paramNames:this.extractParamNames(t),module:s}):Object.keys(s.default).forEach((e=>{this.routes[`${t}:${e}`]={method:e,handler:s.default[e]}})),this.log(`[INFO] Loaded route: ${t}`)}catch(t){this.log(`[ERROR] Failed to load route ${e}: ${t}`)}},s=(e,r="")=>{readdirSync(e,{withFileTypes:!0}).forEach((i=>{const o=join(e,i.name),n=join(r,i.name.replace(".js","")).replace(/\\/g,"/");i.isDirectory()?s(o,n):".js"===extname(i.name)&&t(o,`/${n}`)}))};s(e)}}extractParamNames(e){const t=[];return e.replace(/\[([^\]]+)\]/g,((e,s)=>(t.push(s),"([^/]+)"))),t}setupDefaultRoutes(){this.routes["/:GET"]={method:"GET",handler:()=>({message:"Welcome to ZingJS!"})},this.routes["/index:GET"]={method:"GET",handler:()=>({message:"Hello from ZingJS dynamic route!"})}}async jsonParserMiddleware(e,t,s){let r="";e.on("data",(e=>r+=e)),e.on("end",(()=>{if(e.body={},r)try{e.body=JSON.parse(r)}catch{e.body={},this.log("[WARN] Failed to parse JSON body")}s()}))}corsMiddleware(e,t,s){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),"OPTIONS"===e.method)return t.writeHead(204),void t.end();s()}rateLimitMiddleware(){const e=new Map;return(t,s,r)=>{const i=t.socket.remoteAddress,o=Date.now()+9e5;if(e.has(i)){const t=e.get(i);if(t.count>=100)return s.writeHead(429,{"Content-Type":"application/json"}),void s.end(JSON.stringify({error:"Too many requests, please try again later."}));t.count++}else e.set(i,{count:1,resetTime:o});r()}}async requestHandler(e,t){if(this.log(`[INFO] ${e.method} ${e.url}`),e.query=Object.fromEntries(new URL(e.url,"http://localhost").searchParams),e.params={},this.handleDocsRoute(e,t))return;if(this.handleStaticFiles(e,t))return;let s=0;const r=async()=>{s(e[t]=n[s+1],e)),{}),i={handler:t.module.default[r]};break}}if(i&&"function"==typeof i.handler){const s=await i.handler(e);t.setHeader("Content-Type","json"===this.defaultResponseType?"application/json":"text/plain"),t.end("json"===this.defaultResponseType?JSON.stringify(s):String(s))}else t.writeHead(404),t.end(JSON.stringify({error:"Not Found"})),this.log(`[WARN] ${r} ${s} - 404 Not Found`)}listen(e,t){this.server.listen(e,(()=>{this.log(`[INFO] Server running at http://localhost:${e}`),t&&t()}))}}export default ZingJS;