import express from 'express';
import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import type { WordBank } from '@wordle/shared';
import { createDailyRouter } from './routes/daily.js';
import { createGuessRouter } from './routes/guess.js';
import { createPlayAgainRouter } from './routes/play-again.js';

const __dirname = dirname(fileURLToPath(import.meta.url));

// Load word bank at startup
const wordBankPath = resolve(__dirname, '../../data/word-bank.json');
const wordBank: WordBank = JSON.parse(readFileSync(wordBankPath, 'utf-8'));

const app = express();
app.use(express.json());

// API routes
app.use('/api/daily', createDailyRouter(wordBank));
app.use('/api/guess', createGuessRouter(wordBank));
app.use('/api/play-again', createPlayAgainRouter(wordBank));

// Serve SPA in production
const clientDist = resolve(__dirname, '../../client/dist');
app.use(express.static(clientDist));
app.get('/{*path}', (_req, res) => {
  res.sendFile(resolve(clientDist, 'index.html'));
});

const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

export default app;
