import express from 'express';
import cors from 'cors';
import router from './routes/router.js';
import { getAppPort, getConfig } from './config.js';
import { whisperService } from './services/whisper.service.js';
import { piperService as piperWorker } from './services/piper.service.js';
import { mcpClient } from './services/mcpClient.service.js';

const app = express();

app.use(cors());
app.use(express.json());

// Handle multipart in motor controller separately
app.use('/audio', express.json());
app.use('/motor', express.json());
app.use('/commands', express.json());

// Serve generated TTS audio files to the APK
app.use('/tts-audio', express.static('/tmp/quibot-audio/tts'));

app.use(router);

app.get('/health', (_req, res) => {
  const settings = getConfig();
  res.json({ status: 'ok', settings });
});

const server = app.listen(getAppPort(), async () => {
  console.log(`QuiBot backend listening on port ${getAppPort()}`);
  whisperService.spawn();
  piperWorker.initWav().catch(() => { /* model may not exist yet → lazy init on first TTS call */ });
  try {
    await mcpClient.start();
    console.log('[server] MCP client started');
  } catch (err) {
    console.error(`[server] MCP client failed to start: ${err instanceof Error ? err.message : String(err)}`);
  }
});

async function shutdown(signal: string) {
  console.log(`[server] ${signal} received, shutting down...`);
  server.close(async () => {
    await Promise.all([whisperService.shutdown(), piperWorker.shutdown(), mcpClient.shutdown()]);
    process.exit(0);
  });
}

process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
