import { createRouter } from '../../create-router';
import { readServerSettings, writeServerSettings } from 'officerdb';

type SttConfig = {
  url: string;
};

export async function readSttConfig(): Promise<SttConfig | undefined> {
  const settings = await readServerSettings();
  return settings.stt as SttConfig | undefined;
}

export const sttRouter = createRouter();

sttRouter.get('/', async (ctx) => {
  const stt = await readSttConfig();
  if (!stt) return ctx.json(null);
  return ctx.json(stt);
});

sttRouter.put('/', async (ctx) => {
  const body = await ctx.req.json<SttConfig>();
  const settings = await readServerSettings();
  settings.stt = body;
  await writeServerSettings(settings);
  return ctx.json({ success: true });
});

sttRouter.post('/test', async (ctx) => {
  const body = await ctx.req.json<{ url: string }>();
  if (!body.url) return ctx.json({ error: 'URL required' }, 400);

  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 5000);
    const res = await fetch(`${body.url.replace(/\/+$/, '')}/inference`, {
      method: 'POST',
      body: new FormData(),
      signal: controller.signal,
    });
    clearTimeout(timeout);
    // Whisper will return an error for empty form, but a response means it's reachable
    return ctx.json({ success: true, status: res.status });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return ctx.json({ error: message }, 500);
  }
});
