import http from 'http';
import fs from 'fs';
import path from 'path';

const server = http.createServer((req, res) => {
  // 处理静态文件请求
  let filePath = '.' + req.url;
  
  // 处理根路径
  if (filePath === './') {
    filePath = './index.html';
  }

  // 获取文件扩展名
  const extname = String(path.extname(filePath)).toLowerCase();
  
  // MIME类型映射
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.mjs': 'text/javascript',
    '.ts': 'text/javascript',
    '.tsx': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.wasm': 'application/wasm'
  };

  // 获取内容类型
  const contentType = mimeTypes[extname] || 'application/octet-stream';

  // 读取文件
  fs.readFile(filePath, (error, content) => {
    if (error) {
      if(error.code == 'ENOENT') {
        // 对于HTML、TypeScript、JavaScript文件和根路径，返回index.html
        // 这样React的路由系统就可以处理这些请求
        const urlExt = path.extname(req.url);
        if (req.url.endsWith('.html') || 
            req.url === '/' || 
            !urlExt ||
            urlExt === '.ts' ||
            urlExt === '.tsx' ||
            urlExt === '.js' ||
            urlExt === '.mjs') {
          fs.readFile('./index.html', (error, content) => {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(content, 'utf-8');
          });
        } else {
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('File not found', 'utf-8');
        }
      }
      else {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Server error: ' + error.code, 'utf-8');
      }
    }
    else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});