import { Hono } from 'hono';
import { loadAppConfig, loadNovelsConfig } from './config/loader.ts';
import { ResourceRegistry } from './services/registry.ts';
import { Cache } from './services/cache.ts';
import { createNovelRouter, registerNovelFromConfig } from './routes/novel.ts';

const appConfig = loadAppConfig();
const novelsConfig = loadNovelsConfig();

const registry = new ResourceRegistry();
const cache = new Cache(appConfig.cache.basePath);

for (const def of novelsConfig.novels) {
  try {
    const id = registerNovelFromConfig(def, registry, cache, appConfig);
    console.log(`[init] Registered novel "${def.slug}" as id=${id}`);
  } catch (err) {
    console.error(`[init] Failed to register novel "${def.slug}": ${err instanceof Error ? err.message : err}`);
  }
}

const app = new Hono();
app.route('/qa/requests/novel', createNovelRouter(registry, cache, appConfig));

console.log(`[init] Listening on port ${appConfig.server.port}`);

export default {
  port: appConfig.server.port,
  fetch: app.fetch,
  // TOC scraping can take 15-30s; raise above Bun's 10s default so the first
  // request doesn't time out before the cache is populated.
  idleTimeout: 120,
};
