import express from 'express';
import { getDatabase, saveDatabase } from './db/database.js';
import { createRecipeRoutes } from './routes/recipes.js';
import { createTagRoutes } from './routes/tags.js';
import { createImportRoutes } from './routes/import.js';
import { createHarnessRoutes } from './routes/harness.js';

const app = express();
const port = 3000;
const DB_PATH = 'data/recipes.db';

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// CORS headers for local development
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

// Health check endpoint
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: 'Recipe Manager API is running',
    version: '0.1.0',
  });
});

// Initialize database and routes
async function startServer() {
  try {
    const db = await getDatabase(DB_PATH);
    
    // Mount API routes
    app.use('/api/recipes', createRecipeRoutes(db));
    app.use('/api/tags', createTagRoutes(db));
    app.use('/api/import', createImportRoutes());
    app.use('/api/harness', createHarnessRoutes(process.cwd()));
    
    // Save database periodically (every 5 seconds)
    setInterval(() => {
      try {
        saveDatabase(DB_PATH);
      } catch (error) {
        console.error('Error saving database:', error);
      }
    }, 5000);
    
    // Save database on exit
    process.on('SIGINT', () => {
      console.log('\nSaving database before exit...');
      saveDatabase(DB_PATH);
      process.exit(0);
    });
    
    process.on('SIGTERM', () => {
      console.log('\nSaving database before exit...');
      saveDatabase(DB_PATH);
      process.exit(0);
    });
    
    app.listen(port, () => {
      console.log(`✓ Recipe Manager API running on http://localhost:${port}`);
      console.log(`✓ Database: ${DB_PATH}`);
      console.log(`✓ Endpoints:`);
      console.log(`  Recipes:`);
      console.log(`    GET    /api/recipes       - List recipes`);
      console.log(`    GET    /api/recipes/:id   - Get recipe by ID`);
      console.log(`    POST   /api/recipes       - Create recipe`);
      console.log(`    PUT    /api/recipes/:id   - Update recipe`);
      console.log(`    DELETE /api/recipes/:id   - Delete recipe`);
      console.log(`  Tags:`);
      console.log(`    GET    /api/tags                      - List tags`);
      console.log(`    POST   /api/tags                      - Create tag`);
      console.log(`    PUT    /api/tags/:id                  - Update tag`);
      console.log(`    DELETE /api/tags/:id                  - Delete tag`);
      console.log(`    GET    /api/tags/recipes/:id/tags     - Get recipe tags`);
      console.log(`    POST   /api/tags/recipes/:id/tags     - Assign tag`);
      console.log(`    DELETE /api/tags/recipes/:id/tags/:id - Remove tag`);
      console.log(`  Import:`);
      console.log(`    POST   /api/import/url                - Import recipe foundation data from URL`);
      console.log(`  Harness:`);
      console.log(`    GET    /api/harness/status            - Mission Control progress/status feed`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

startServer();
