import { createRouter } from '../../create-router';
import { readdirSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { readServerSettings, writeServerSettings } from 'officerdb';
import { chatProvidersRouter } from './chat-providers';
import { smtpRouter } from './smtp';
import { ttsRouter } from './tts';
import { sttRouter } from './stt';
import { ocrRouter } from './ocr';

export const serverSettingsRouter = createRouter();

serverSettingsRouter.route('/chat-providers', chatProvidersRouter);
serverSettingsRouter.route('/smtp', smtpRouter);
serverSettingsRouter.route('/tts', ttsRouter);
serverSettingsRouter.route('/stt', sttRouter);
serverSettingsRouter.route('/ocr', ocrRouter);

export { readServerSettings as readSettings };

serverSettingsRouter.get('/settings', async (ctx) => {
  return ctx.json(await readServerSettings());
});

serverSettingsRouter.put('/', async (ctx) => {
  const body = await ctx.req.json();
  const settings = await readServerSettings();
  const updated = { ...settings, ...body };
  await writeServerSettings(updated);
  return ctx.json(updated);
});

serverSettingsRouter.get('/plugins', async (ctx) => {
  const pluginsDir = join(import.meta.dir, '../../../workspaces/plugins');
  const settings = await readServerSettings();
  const pluginSettings: Record<string, boolean> = (settings.plugins as Record<string, boolean>) ?? {};

  const plugins: { id: string; name: string; description: string; enabled: boolean }[] = [];

  if (!existsSync(pluginsDir)) return ctx.json(plugins);

  const dirs = readdirSync(pluginsDir, { withFileTypes: true }).filter((d) => d.isDirectory());

  for (const dir of dirs) {
    const hasServer = existsSync(join(pluginsDir, dir.name, 'server', 'index.ts'));
    const hasClient = existsSync(join(pluginsDir, dir.name, 'client', 'index.ts'));
    if (!hasServer && !hasClient) continue;

    const mainIndex = join(pluginsDir, dir.name, 'index.ts');
    if (!existsSync(mainIndex)) continue;

    const mod = await import(mainIndex);
    const meta = mod.plugin ?? { id: dir.name, name: dir.name, description: '' };
    plugins.push({
      id: meta.id,
      name: meta.name,
      description: meta.description,
      enabled: pluginSettings[meta.id] !== false,
    });
  }

  return ctx.json(plugins);
});
