import crypto from 'crypto';

export default (router, tpl) => {
  router.get(/^\/tag_image\/(?<tag>.+)$/, async (req, res) => {
    const tag = decodeURIComponent(req.params.tag);

    // Create a deterministic hash from the tag
    const hash = crypto.createHash('md5').update(tag).digest('hex');

    // Escape character for SVG
    const escapeXml = (unsafe) => {
      return unsafe.replace(/[<>&'"]/g, (c) => {
        switch (c) {
          case '<': return '&lt;';
          case '>': return '&gt;';
          case '&': return '&amp;';
          case '\'': return '&apos;';
          case '"': return '&quot;';
        }
      });
    };

    const displayTag = escapeXml(tag);

    // Generate colors from hash
    const c1 = '#' + hash.substring(0, 6);
    const c2 = '#' + hash.substring(6, 12);
    const c3 = '#' + hash.substring(12, 18);

    // Generate some deterministic numbers for shapes
    const n1 = parseInt(hash.substring(18, 20), 16);
    const n2 = parseInt(hash.substring(20, 22), 16);

    const svg = `
      <svg width="300" height="150" viewBox="0 0 300 150" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" style="stop-color:${c1};stop-opacity:1" />
            <stop offset="100%" style="stop-color:${c2};stop-opacity:1" />
          </linearGradient>
        </defs>
        <rect width="300" height="150" fill="url(#grad)" />
        <circle cx="${n1}%" cy="${n2}%" r="${(n1 + n2) / 4}" fill="${c3}" fill-opacity="0.3" />
        <circle cx="${100 - n1}%" cy="${100 - n2}%" r="${(n1 + n2) / 3}" fill="${c3}" fill-opacity="0.2" />
        <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="24" fill="#fff" fill-opacity="0.9" font-weight="bold">${displayTag}</text>
      </svg>
    `.trim();

    res.writeHead(200, {
      'Content-Type': 'image/svg+xml',
      'Cache-Control': 'public, max-age=86400'
    });
    res.end(svg);
  });
  return router;
};
