import { Hono } from 'hono';
import { existsSync, readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';

/**
 * Serves the OpenAPI spec at /openapi.yaml and a Redoc HTML viewer at /docs.
 *
 * Any language can fetch /openapi.yaml and generate a client with
 * openapi-generator. The /docs HTML viewer is a thin Redoc wrapper.
 */
export function createOpenApiRoutes(specPath?: string): Hono {
  const app = new Hono();

  const defaultPath = join(
    dirname(fileURLToPath(import.meta.url)),
    '..',
    'openapi.yaml',
  );
  const path = specPath ?? defaultPath;

  app.get('/openapi.yaml', (c) => {
    if (!existsSync(path)) {
      return c.text('OpenAPI spec not found', 404);
    }
    const content = readFileSync(path, 'utf-8');
    c.header('Content-Type', 'application/yaml; charset=utf-8');
    return c.body(content);
  });

  app.get('/docs', (c) => {
    c.header('Content-Type', 'text/html; charset=utf-8');
    return c.body(redocHtml());
  });

  return app;
}

function redocHtml(): string {
  return `<!DOCTYPE html>
<html>
  <head>
    <title>Shade API Reference</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <style>body { margin: 0; padding: 0; }</style>
  </head>
  <body>
    <redoc spec-url="/openapi.yaml"></redoc>
    <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
  </body>
</html>`;
}
