import express from 'express';
import fs from 'fs';
import path from 'path';
import Database from 'better-sqlite3';

const PORT = parseInt(process.env.BACKEND_PORT || '7404', 10);
const WORKSPACE = path.resolve(import.meta.dirname, '..');

// Load workspace/.env manually (no dotenv dep needed)
const envPath = path.join(WORKSPACE, '.env');
if (fs.existsSync(envPath)) {
  for (const line of fs.readFileSync(envPath, 'utf-8').split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq).trim();
    const val = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, '');
    if (!process.env[key]) process.env[key] = val;
  }
}

// Open SQLite database
const db = Database(path.join(WORKSPACE, 'app.db'));
db.pragma('journal_mode = WAL');

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

// Health check
app.get('/api/health', (_req, res) => {
  res.json({ status: 'ok' });
});

// 404 catch-all
app.use((_req, res) => {
  res.status(404).json({ error: 'Not found' });
});

const server = app.listen(PORT, () => {
  console.log(`[backend] Listening on port ${PORT}`);
});

server.on('error', (err: NodeJS.ErrnoException) => {
  console.error(`[backend] Server error: ${err.message}`);
  process.exit(1);
});

// Keep process alive — prevent exit on unhandled rejection
process.on('unhandledRejection', (err) => {
  console.error('[backend] Unhandled rejection:', err);
});
