import express, { Request, Response } from 'express';
import { existsSync } from 'fs';
import { join, resolve, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filenameUiStatic = fileURLToPath(import.meta.url);
const __dirnameUiStatic = dirname(__filenameUiStatic);

/**
 * Root redirect + built-UI static hosting + the headless app-harness page,
 * extracted verbatim from createCoreServer (bridge/server.ts). This module
 * lives in the same directory as server.ts, so the ../../ui/dist resolution
 * is identical at runtime.
 */
export function mountUiStatic(app: express.Application): void {
  // Redirect root to UI
  app.get('/', (_req: Request, res: Response) => {
    res.redirect('/ui');
  });

  const uiDistPath = resolve(join(__dirnameUiStatic, '../../ui/dist'));
  if (existsSync(uiDistPath)) {
    app.use('/ui', express.static(uiDistPath));
    app.get('/ui/*', (_req, res) => {
      res.sendFile(join(uiDistPath, 'index.html'));
    });
    // Headless test-harness page for workspace-app E2E (Task 5/6).
    // Must be registered BEFORE any SPA catch-all and BEFORE space-api routes
    // so that the app-harness auth middleware (mounted below) sees the request.
    // The harness JS/CSS chunks are served by the existing /ui static mount
    // because Vite builds them with base: '/ui/' → /ui/assets/… paths.
    app.get('/app-harness', (_req, res) => {
      res.sendFile(join(uiDistPath, 'app-harness.html'));
    });
  }
}
