import express from 'express';
import path from 'path';
import dotenv from 'dotenv';
import rateLimit from 'express-rate-limit';
import type { Database } from 'sql.js';
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 { createImportLocalRoutes } from './routes/importLocal.js';
import { createHarnessRoutes } from './routes/harness.js';

// Load environment variables
dotenv.config();

const app = express();
const port = parseInt(process.env.PORT || '3000', 10);
const DB_PATH = process.env.DATABASE_PATH || 'data/recipes.db';
const ALLOWED_ORIGIN = process.env.ALLOWED_ORIGIN || '*';
const API_KEY = process.env.API_KEY; // if set, will be required for write methods

// Rate limiter for import endpoints
const importRateLimit = rateLimit({
  windowMs: parseInt(process.env.IMPORT_RATE_LIMIT_WINDOW_MS || '60000', 10),
  max: parseInt(process.env.IMPORT_RATE_LIMIT_MAX_REQUESTS || '10', 10),
  message: { success: false, error: 'Too many import requests, please try again later.' },
  standardHeaders: true,
  legacyHeaders: false,
});

// Database dirty tracking for smarter saves
let dbDirty = true; // start dirty to ensure initial save
const originalSave = saveDatabase;
const dirtySave = (dbPath: string = 'data/recipes.db') => {
  if (dbDirty) {
    originalSave(dbPath);
    dbDirty = false;
  }
};
// Monkey-patch repositories to set dirty flag on mutations
// (Will patch specific db.run calls later)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static images from data/images directory
app.use('/images', express.static(path.join(process.cwd(), 'data', 'images')));

// CORS headers (configurable)
app.use((req, res, next) => {
  const origin = req.headers.origin as string | undefined;
  if (ALLOWED_ORIGIN === '*') {
    res.header('Access-Control-Allow-Origin', '*');
  } else if (origin && origin === ALLOWED_ORIGIN) {
    res.header('Access-Control-Allow-Origin', 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();
  }
});

// API key authentication middleware (only enforce if API_KEY is configured)
const requireApiKeyForWrite: express.RequestHandler = (req, res, next) => {
  const safeMethods = ['GET', 'HEAD', 'OPTIONS'];
  if (safeMethods.includes(req.method)) {
    return next();
  }
  if (!API_KEY) {
    return next(); // no auth configured
  }
  const key = req.headers['x-api-key'] ?? req.query['api_key'] as string | undefined;
  if (!key || key !== API_KEY) {
    return res.status(401).json({ success: false, error: 'Invalid or missing API key' });
  }
  next();
};

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

// 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);
    
    // Patch db.run to set dirty flag on any write
    const originalRun = db.run.bind(db);
    db.run = function(this: any, sql: string, params?: any[]): Database {
      dbDirty = true;
      return originalRun(sql, params);
    };
    
    // Mount API routes (write routes protected by API key if configured)
    app.use('/api/recipes', requireApiKeyForWrite, createRecipeRoutes(db));
    app.use('/api/tags', requireApiKeyForWrite, createTagRoutes(db));
    app.use('/api/import', importRateLimit, requireApiKeyForWrite, createImportRoutes());
    app.use('/api/import/local', importRateLimit, requireApiKeyForWrite, createImportLocalRoutes());
    // Harness routes are internal; keep unprotected but consider restricting in production
    app.use('/api/harness', createHarnessRoutes(process.cwd()));
    
    // Save database periodically (only if dirty)
    setInterval(() => {
      try {
        dirtySave(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(`✓ Static images: http://localhost:${port}/images`);
      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(`    POST   /api/import/local              - Import recipes from local files (.html/.txt)`);
      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();
