import fs from 'fs';
import fsp from 'fs/promises';
import http from 'http';
import path from 'path';

const ROUTE_PREFIX = '/deepfilter-assets/';
const ALLOWED_CDN_PATH_PREFIX =
  'AI/models/datas/noise_suppression/deepfilternet3/';
const CDN_BASE_URL = 'https://cdn.mezon.ai/';
const CACHE_DIR = '/root/.config/pulse/deepfilter-assets';

const guessContentType = (filePath: string): string => {
  if (filePath.endsWith('.wasm')) return 'application/wasm';
  if (filePath.endsWith('.gz')) return 'application/gzip';
  if (filePath.endsWith('.json')) return 'application/json';
  return 'application/octet-stream';
};

const sendFile = async (res: http.ServerResponse, filePath: string) => {
  const stat = await fsp.stat(filePath);
  res.writeHead(200, {
    'Content-Type': guessContentType(filePath),
    'Content-Length': stat.size,
    'Cache-Control': 'public, max-age=31536000, immutable'
  });
  fs.createReadStream(filePath).pipe(res);
};

const deepfilterAssetsRouteHandler = async (
  req: http.IncomingMessage,
  res: http.ServerResponse
) => {
  const routePath = (req.url || '').split('?')[0] || '';
  if (!routePath.startsWith(ROUTE_PREFIX)) {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Not found' }));
    return;
  }

  const relativePath = decodeURIComponent(routePath.slice(ROUTE_PREFIX.length));
  if (!relativePath.startsWith(ALLOWED_CDN_PATH_PREFIX)) {
    res.writeHead(403, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Forbidden' }));
    return;
  }

  const resolvedPath = path.resolve(CACHE_DIR, relativePath);
  const cacheBasePath = path.resolve(CACHE_DIR);
  if (!resolvedPath.startsWith(cacheBasePath)) {
    res.writeHead(403, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Forbidden' }));
    return;
  }

  try {
    await sendFile(res, resolvedPath);
    return;
  } catch {
    // Cache miss; continue to fetch from upstream.
  }

  await fsp.mkdir(path.dirname(resolvedPath), { recursive: true });

  const upstreamUrl = new URL(relativePath, CDN_BASE_URL).toString();
  const upstream = await fetch(upstreamUrl);
  if (!upstream.ok) {
    res.writeHead(upstream.status, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Upstream fetch failed' }));
    return;
  }

  const body = Buffer.from(await upstream.arrayBuffer());
  const tempPath = `${resolvedPath}.tmp-${Date.now()}`;
  await fsp.writeFile(tempPath, body);
  await fsp.rename(tempPath, resolvedPath);

  res.writeHead(200, {
    'Content-Type':
      upstream.headers.get('content-type') || guessContentType(resolvedPath),
    'Content-Length': body.length,
    'Cache-Control': 'public, max-age=31536000, immutable'
  });
  res.end(body);
};

export { deepfilterAssetsRouteHandler };
