const http = require('http');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

// Parse command line arguments
const args = process.argv.slice(2);
const OPEN_BROWSER = !args.includes('--no-open');

console.log('Initializing server...');

const CONFIG = {
  PORT: 3000,
  PROJECT_ROOT: path.resolve(__dirname, '..'),
  EDITOR_PATH: path.join(__dirname, 'standalone-editor/test-bs5-editor.html'),
  ASSETS_DIR: path.join(__dirname, 'standalone-editor/assets'),
  CONTENT_TYPES: {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.ico': 'image/x-icon',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2',
    '.ttf': 'font/ttf',
    '.eot': 'application/vnd.ms-fontobject'
  }
};

console.log('Config loaded');
console.log('Editor path:', CONFIG.EDITOR_PATH);
console.log('Assets directory:', CONFIG.ASSETS_DIR);

const server = http.createServer((req, res) => {
  if (req.url === '/' || req.url === '/index.html') {
    fs.readFile(CONFIG.EDITOR_PATH, (err, content) => {
      if (err) {
        console.error('Error loading editor file:', err);
        res.writeHead(500);
        res.end(`Error loading the editor file: ${err.code}`);
        return;
      }
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(content, 'utf-8');
    });
    return;
  }

  // Special handling for test HTML files
  if (req.url.startsWith('/standalone-editor/') && req.url.endsWith('.html')) {
    const htmlPath = path.join(__dirname, req.url);
    fs.readFile(htmlPath, (err, content) => {
      if (err) {
        console.error('Error loading HTML file:', err);
        res.writeHead(500);
        res.end(`Error loading HTML file: ${err.code}`);
        return;
      }
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(content, 'utf-8');
    });
    return;
  }
  
  // Extract the request path and remove any query parameters
  let reqPath = decodeURIComponent(req.url.split('?')[0]);
  let originalReqPath = reqPath;

  // Pattern-based URL transforms
  const patternTransforms = [
    // Handle Drupal module paths with both contrib and direct patterns
    {
      pattern: /^\/modules\/(?:contrib\/)?dxpr_builder\/dxpr_builder\/(.+)$/,
      transform: (match) => match[1]
    },
    {
      pattern: /^\/modules\/(?:contrib\/)?dxpr_builder\/(.+)$/,
      transform: (match) => match[1]
    },
    // Handle specific vendor paths
    {
      pattern: /^\/dxpr_builder\/vendor\/managed\/(.+)$/,
      transform: (match) => `vendor/${match[1]}`
    },
    {
      pattern: /^\/dxpr_builder\/vendor\/unmanaged\/(.+)$/,
      transform: (match) => `vendor/unmanaged/${match[1]}`
    },
    // Handle core and remaining dxpr_builder paths
    {
      pattern: /^\/core\/(.+)$/,
      transform: (match) => `core/${match[1]}`
    },
    {
      pattern: /^\/dxpr_builder\/(.+)$/,
      transform: (match) => match[1]
    },
    // Handle css, js and other root-level paths
    {
      pattern: /^\/css\/(.+)$/,
      transform: (match) => `css/${match[1]}`
    },
    {
      pattern: /^\/js\/(.+)$/,
      transform: (match) => `js/${match[1]}`
    },
    {
      pattern: /^\/standalone-editor\/assets\/(.+)$/,
      transform: (match) => match[1]
    }
  ];

  // Apply pattern transforms
  for (const { pattern, transform } of patternTransforms) {
    const match = reqPath.match(pattern);
    if (match) {
      reqPath = transform(match);
      break;
    }
  }
  
  // Build the file path in assets directory
  const filePath = path.join(CONFIG.ASSETS_DIR, reqPath);
  
  // Handle missing files
  if (!fs.existsSync(filePath)) {
    // Special handling for debug/favicon/csrf files
    if (reqPath.includes('debug') || reqPath.includes('favicon.ico') || reqPath.includes('csrf')) {
      if (reqPath.endsWith('.js')) {
        res.writeHead(200, { 'Content-Type': 'text/javascript' });
        res.end('// Empty placeholder');
      } else {
        res.writeHead(204);
        res.end();
      }
      return;
    }

    // Try alternative paths based on file types
    const alternativePaths = [
      // Try with or without 'managed' in the path
      reqPath.replace(/^vendor\//, 'vendor/managed/'),
      reqPath.replace(/^vendor\/managed\//, 'vendor/'),
      
      // Try css alternatives
      ...(reqPath.endsWith('.css') ? [
        `css/${path.basename(reqPath)}`,
        `vendor/managed/${path.basename(reqPath)}`,
        reqPath.replace(/^vendor\//, 'css/')
      ] : []),
      
      // Try js alternatives
      ...(reqPath.endsWith('.js') ? [
        `js/${path.basename(reqPath)}`,
        `vendor/managed/${path.basename(reqPath)}`,
        reqPath.replace(/^vendor\//, 'js/')
      ] : [])
    ];

    // Try all alternative paths
    for (const altPath of alternativePaths) {
      const altFilePath = path.join(CONFIG.ASSETS_DIR, altPath);
      if (fs.existsSync(altFilePath)) {
        console.log(`Found alternative path: ${altFilePath}`);
        fs.readFile(altFilePath, (err, content) => {
          if (err) {
            console.error('Error reading file:', err);
            res.writeHead(500);
            res.end();
            return;
          }
          const contentType = CONFIG.CONTENT_TYPES[path.extname(altFilePath)] || 'text/plain';
          res.writeHead(200, { 'Content-Type': contentType });
          res.end(content, 'utf-8');
        });
        return;
      }
    }
    
    // For all other missing files, return 404
    console.error('File not found:', filePath);
    res.writeHead(404);
    res.end();
    return;
  }
  
  // File exists, serve it
  fs.readFile(filePath, (err, content) => {
    if (err) {
      console.error('Error reading file:', err);
      res.writeHead(500);
      res.end();
      return;
    }
    const contentType = CONFIG.CONTENT_TYPES[path.extname(filePath)] || 'text/plain';
    res.writeHead(200, { 'Content-Type': contentType });
    res.end(content, 'utf-8');
  });
});

server.listen(CONFIG.PORT, () => {
  console.log(`Server listening on port ${CONFIG.PORT}`);
  
  if (OPEN_BROWSER) {
    const urls = [
      `http://localhost:${CONFIG.PORT}/standalone-editor/test-bs5-anon.html`,
      `http://localhost:${CONFIG.PORT}/standalone-editor/test-bs5-editor.html`
    ];

    const commands = {
      darwin: (url) => `open "${url}"`,
      win32: (url) => `start "${url}"`,
      linux: (url) => `xdg-open "${url}"`
    };

    const openCommand = commands[process.platform] || commands.linux;
    
    console.log('Opening browsers...');
    urls.forEach(url => {
      exec(openCommand(url));
    });
  }
}); 