const path = require('path');
const dotenv = require('dotenv');

dotenv.config({
  path: __dirname + '/.env'
});
console.log('dotenv loaded OPENAI_API_KEY:', !!process.env.OPENAI_API_KEY);

const express = require('express');
const { chatController } = require('./controllers/chatController');

const app = express();
const port = process.env.PORT || 3001;
const publicPath = path.join(__dirname, '../frontend');

app.use(express.json());
app.use(express.static(publicPath));

app.get('/health', (req, res) => {
  res.json({ status: 'ok', service: 'gnr-ai-chatbot' });
});

app.post('/api/chat', chatController);

app.get('/', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'));
});

app.use((req, res) => {
  if (req.path.startsWith('/api/')) {
    return res.status(404).json({ error: 'Not found' });
  }
  return res.sendFile(path.join(publicPath, 'index.html'));
});

app.use((err, req, res, next) => {
  console.error('Server error:', err);
  res.status(500).json({ error: 'Internal server error' });
});

app.listen(port, () => {
  console.log(`GNR AI chatbot server running on http://localhost:${port}`);
});
