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

type OcrConfig = {
  url: string;
  model: string;
};

export async function readOcrConfig(): Promise<OcrConfig | undefined> {
  const settings = await readServerSettings();
  return settings.ocr as OcrConfig | undefined;
}

export const ocrRouter = createRouter();

ocrRouter.get('/', async (ctx) => {
  const ocr = await readOcrConfig();
  if (!ocr) return ctx.json(null);
  return ctx.json(ocr);
});

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

// GET: it asks a provider what models it has and returns the answer. Nothing is written, and the only
// input is a URL — no credential, so a query string is the right place for it. Kept POST until
// 2026-08-06 purely by habit, and the permission model reads the method.
ocrRouter.get('/models', async (ctx) => {
  const body = { url: ctx.req.query('url') ?? '' };
  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(/\/+$/, '')}/v1/models`, {
      signal: controller.signal,
    });
    clearTimeout(timeout);
    if (!res.ok) return ctx.json({ error: `Server returned ${res.status}` }, 500);
    const json = (await res.json()) as { data?: { id: string }[] };
    const models = (json.data ?? []).map((m) => m.id);
    return ctx.json({ models });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return ctx.json({ error: message }, 500);
  }
});

ocrRouter.post('/test', async (ctx) => {
  const body = await ctx.req.json<OcrConfig>();
  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(/\/+$/, '')}/v1/models`, {
      signal: controller.signal,
    });
    clearTimeout(timeout);
    if (!res.ok) return ctx.json({ error: `Server returned ${res.status}` }, 500);
    return ctx.json({ success: true });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return ctx.json({ error: message }, 500);
  }
});
