const express = require('express');
const path = require('path');
const sqlite3 = require('better-sqlite3');

const identityRoutes = require('./routes/identity');
const cognitionRoutes = require('./routes/cognition');
const memoryRoutes = require('./routes/memory');
const profilesRoutes = require('./routes/profiles');
const agentsRoutes = require('./routes/agents');
const documentsRoutes = require('./routes/documents');
// const uploadRoutes = require('./routes/upload');  // TODO: install multer+adm-zip deps
const authMiddleware = require('./middleware/auth');

const DB_PATH = path.join(__dirname, '..', 'brain.db');
const PORT = process.env.BRAIN_API_PORT || 3914;

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

// 前端静态文件
app.use(express.static(path.join(__dirname, '..', 'frontend')));

let db;
try {
  db = sqlite3(DB_PATH);
  db.pragma('journal_mode = WAL');
  db.pragma('foreign_keys = ON');
} catch (err) {
  console.error('DB error');
  process.exit(1);
}

app.use((req, _res, next) => { req.db = db; next(); });

app.get('/brain/health', (_req, res) => {
  res.json({ status: 'ok', service: 'persona-brain-db', timestamp: new Date().toISOString() });
});

app.use('/brain/identity', authMiddleware, identityRoutes);
app.use('/brain/cognition', authMiddleware, cognitionRoutes);
app.use('/brain/memory', authMiddleware, memoryRoutes);
app.use('/brain/profiles', authMiddleware, profilesRoutes);
app.use('/brain/agents', authMiddleware, agentsRoutes);
app.use('/brain/documents', documentsRoutes);
// app.use('/brain/documents', uploadRoutes);  // TODO: enable after installing multer+adm-zip

app.use((err, _req, res, _next) => {
  res.status(500).json({ error: true, message: 'Internal error' });
});

app.listen(PORT, () => console.log('brain-db API :' + PORT));
module.exports = app;
