const { Router } = require("express");
const sharp = require("sharp");
const store = require("../store");

const router = Router();

const POSTER_WIDTH = 750;
const POSTER_HEIGHT = 1200;

function wrapText(text, maxCharsPerLine) {
  const lines = [];
  let current = "";
  for (const ch of text) {
    if (ch === "\n") {
      lines.push(current);
      current = "";
    } else if (current.length >= maxCharsPerLine) {
      lines.push(current);
      current = ch;
    } else {
      current += ch;
    }
  }
  if (current) lines.push(current);
  return lines;
}

function buildPosterSvg(dream, interpretation) {
  const dreamLines = wrapText(`梦：${dream}`, 18).slice(0, 10);
  const interpLines = wrapText(interpretation, 18);

  const titleY = 80;
  const dreamCardY = 140;
  const interpCardY = 400;
  const lineHeight = 36;
  const dreamCardH = dreamLines.length * lineHeight + 80;
  const interpCardH = interpLines.length * lineHeight + 80;

  const dreamTextSvg = dreamLines
    .map((l, i) => `<text x="48" y="${48 + i * lineHeight}" font-size="28" fill="#333">${escapeXml(l)}</text>`)
    .join("\n");

  const interpTextSvg = interpLines
    .map((l, i) => `<text x="48" y="${48 + i * lineHeight}" font-size="28" fill="#333">${escapeXml(l)}</text>`)
    .join("\n");

  const footerY = interpCardY + interpCardH + 60;

  return `<svg xmlns="http://www.w3.org/2000/svg" width="${POSTER_WIDTH}" height="${Math.max(POSTER_HEIGHT, footerY + 80)}">
    <defs>
      <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stop-color="#1a1a2e"/>
        <stop offset="100%" stop-color="#16213e"/>
      </linearGradient>
    </defs>
    <rect width="100%" height="100%" fill="url(#bg)"/>
    <text x="375" y="${titleY}" text-anchor="middle" font-size="48" font-weight="bold" fill="#e0c77c">周公解梦</text>
    <text x="375" y="${titleY + 32}" text-anchor="middle" font-size="20" fill="#a0a0b0">— AI 智能梦境解析 —</text>
    <rect x="24" y="${dreamCardY}" width="702" height="${dreamCardH}" rx="16" fill="#ffffff" opacity="0.95"/>
    <text x="48" y="${dreamCardY + 38}" font-size="24" font-weight="bold" fill="#1a1a2e">梦境描述</text>
    ${dreamTextSvg}
    <rect x="24" y="${interpCardY}" width="702" height="${interpCardH}" rx="16" fill="#ffffff" opacity="0.95"/>
    <text x="48" y="${interpCardY + 38}" font-size="24" font-weight="bold" fill="#1a1a2e">解梦分析</text>
    ${interpTextSvg}
    <text x="375" y="${footerY}" text-anchor="middle" font-size="22" fill="#606070">— 周公解梦 · AI 智能解析 —</text>
  </svg>`;
}

function escapeXml(s) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

router.get("/generate-post", async (req, res) => {
  try {
    const { record_id } = req.query;
    if (!record_id) {
      return res.status(400).json({ error: "缺少 record_id 参数" });
    }

    const record = store.getRecord(record_id);
    if (!record) {
      return res.status(404).json({ error: "记录不存在" });
    }

    const svg = buildPosterSvg(record.dream, record.interpretation);
    const png = await sharp(Buffer.from(svg)).png().toBuffer();

    res.set("Content-Type", "image/png");
    res.send(png);
  } catch (err) {
    console.error("生成海报失败:", err.message);
    res.status(500).json({ error: "生成海报失败" });
  }
});

module.exports = router;
