import {
  CompilationService
} from "./chunk-JGAJAREK.js";
import "./chunk-HMLY7DHA.js";

// src/http.ts
import { Hono } from "hono";
import { cors } from "hono/cors";

// src/middleware/body-limit.ts
function bodyLimit(maxBytes = 50 * 1024) {
  return async (c, next) => {
    const contentLength = c.req.header("Content-Length");
    if (contentLength && parseInt(contentLength, 10) > maxBytes) {
      return c.json(
        {
          ok: false,
          diagnostics: [
            {
              severity: "error",
              code: "PAYLOAD_TOO_LARGE",
              message: `Request body exceeds ${maxBytes} bytes`
            }
          ]
        },
        413
      );
    }
    return next();
  };
}

// src/middleware/timeout.ts
function timeout(ms = 1e4) {
  return async (c, next) => {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), ms);
    try {
      const result = await Promise.race([
        next(),
        new Promise((_, reject) => {
          controller.signal.addEventListener("abort", () => {
            reject(new Error("Request timeout"));
          });
        })
      ]);
      return result;
    } catch (err) {
      if (err instanceof Error && err.message === "Request timeout") {
        return c.json(
          {
            ok: false,
            diagnostics: [
              {
                severity: "error",
                code: "REQUEST_TIMEOUT",
                message: `Request timed out after ${ms}ms`
              }
            ]
          },
          504
        );
      }
      throw err;
    } finally {
      clearTimeout(timer);
    }
  };
}

// src/middleware/logger.ts
function structuredLogger() {
  return async (c, next) => {
    const start = Date.now();
    await next();
    const durationMs = Date.now() - start;
    const entry = {
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      method: c.req.method,
      path: new URL(c.req.url).pathname,
      status: c.res.status,
      durationMs
    };
    console.log(JSON.stringify(entry));
  };
}

// src/http.ts
function createApp(options = {}) {
  const app = new Hono();
  let service = options.service ?? null;
  let initPromise = null;
  async function getService() {
    if (service) return service;
    if (!initPromise) {
      initPromise = CompilationService.create().then((s) => {
        service = s;
        return s;
      });
    }
    return initPromise;
  }
  app.use("*", cors({ origin: options.corsOrigin ?? "*" }));
  if (options.production) {
    app.use("*", bodyLimit(options.maxBodyBytes));
    app.use("*", timeout(options.timeoutMs));
    app.use("*", structuredLogger());
  }
  if (options.apiKey) {
    app.use("*", async (c, next) => {
      if (new URL(c.req.url).pathname === "/health") {
        return next();
      }
      const auth = c.req.header("Authorization");
      if (auth !== `Bearer ${options.apiKey}`) {
        return c.json({ ok: false, error: "Unauthorized" }, 401);
      }
      return next();
    });
  }
  app.get("/health", async (c) => {
    const ready = service !== null;
    const base = { ok: true, version: "1.4.0", ready, uptime: process.uptime() };
    if (ready) {
      return c.json({ ...base, cache: service.getCacheStats() });
    }
    return c.json(base);
  });
  app.post("/compile", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.compile(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.post("/validate", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.validate(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.post("/translate", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.translate(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.post("/generate-tests", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.generateTests(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.post("/generate-component", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.generateComponent(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.post("/diff", async (c) => {
    const svc = await getService();
    const body = await c.req.json();
    const result = svc.diff(body);
    return c.json(result, result.ok ? 200 : 422);
  });
  app.get("/cache/stats", async (c) => {
    const svc = await getService();
    return c.json(svc.getCacheStats());
  });
  app.delete("/cache", async (c) => {
    const svc = await getService();
    svc.clearCache();
    return c.json({ ok: true });
  });
  app.onError((err, c) => {
    return c.json(
      {
        ok: false,
        diagnostics: [
          {
            severity: "error",
            code: "INTERNAL_ERROR",
            message: err instanceof Error ? err.message : String(err)
          }
        ]
      },
      500
    );
  });
  return app;
}
async function serve(options = {}) {
  const { serve: honoServe } = await import("@hono/node-server");
  const app = createApp(options);
  const port = options.port ?? 3001;
  honoServe({ fetch: app.fetch, port });
  console.log(`LokaScript Compilation Service listening on http://localhost:${port}`);
}
export {
  createApp,
  serve
};
//# sourceMappingURL=http.js.map