import express from 'express';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url';
import { corsMiddleware } from './middleware/cors.js';
import windowsRoutes from './routes/windows.js';
import modelStateRoutes from './routes/model-state.js';
import logsRoutes from './routes/logs.js';
import proxyRoutes from './routes/proxy.js';
import { getDatabase } from './services/database.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Runtime mode detection
const isProd = process.env.NODE_ENV === 'production';
// Port: 3067 in prod, 3068 in dev (Vite uses 3067 in dev)
const PORT = process.env.PORT || (isProd ? 3067 : 3068);
// Config directory: ~/.config/shella/
const CONFIG_DIR = path.join(os.homedir(), '.config', 'shella');
// Log file: ~/.config/shella/shella.log in prod, ./dev.log in dev
const LOG_FILE = isProd
    ? path.join(CONFIG_DIR, 'shella.log')
    : path.resolve(process.cwd(), 'dev.log');
/**
 * Ensure config directory exists
 */
function ensureConfigDir() {
    if (!fs.existsSync(CONFIG_DIR)) {
        fs.mkdirSync(CONFIG_DIR, { recursive: true });
        console.log(`[shella-server] Created config directory: ${CONFIG_DIR}`);
    }
}
const app = express();
// CORS - allow all origins for mobile debugging
app.use(corsMiddleware);
// JSON body parsing
app.use(express.json());
// Health check
app.get('/health', (_req, res) => res.json({ status: 'ok' }));
// Mount API routes
app.use('/__shella', windowsRoutes);
app.use('/__model-state', modelStateRoutes);
app.use('/__logs', logsRoutes);
app.use('/api', proxyRoutes);
// Production: serve static files from dist/web/
if (isProd) {
    const webDir = path.join(__dirname, '..', 'web');
    if (fs.existsSync(webDir)) {
        console.log(`[shella-server] Serving static files from ${webDir}`);
        app.use(express.static(webDir));
        // SPA fallback: serve index.html for non-API routes
        // Express 5 requires named wildcards, use {*path} syntax
        app.get('{*path}', (req, res, next) => {
            // Skip API routes
            if (req.path.startsWith('/api') ||
                req.path.startsWith('/__shella') ||
                req.path.startsWith('/__model-state') ||
                req.path.startsWith('/__logs') ||
                req.path.startsWith('/health')) {
                return next();
            }
            res.sendFile(path.join(webDir, 'index.html'));
        });
    }
    else {
        console.warn(`[shella-server] Warning: ${webDir} not found. Static serving disabled.`);
    }
}
/**
 * Start the server
 */
async function start() {
    // Ensure config directory exists in prod
    if (isProd) {
        ensureConfigDir();
    }
    // Initialize database before starting server
    await getDatabase();
    // Clear/create log file on server start
    const logDir = path.dirname(LOG_FILE);
    if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true });
    }
    fs.writeFileSync(LOG_FILE, `--- Shella server started ${new Date().toISOString()} ---\n`);
    app.listen(PORT, () => {
        console.log(`[shella-server] Running on http://localhost:${PORT}`);
        console.log(`[shella-server] Mode: ${isProd ? 'production' : 'development'}`);
        console.log(`[shella-server] Logging to ${LOG_FILE}`);
    });
}
start().catch((err) => {
    console.error('[shella-server] Failed to start:', err);
    process.exit(1);
});
export { CONFIG_DIR };
