#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  buildFeedThumbnailSvg,
  buildThumbnailSvg,
  extractCoverSignals,
  generateHtmlThumbnail,
  resolveCoverDataUri,
} from '../mindspace-thumbnails.mjs';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const outputDir = path.join(root, 'public', 'thumbnail-demo');
const samples = [
  {
    id: 'malaysia-travel',
    file: path.join(root, 'MindSpace', 'john', 'malaysia-travel-guide.html'),
    meta: {
      tag: '旅行攻略',
      subtitle: '马来西亚深度游',
      cover: 'https://images.unsplash.com/photo-1596422846543-75c6fc197f07?auto=format&fit=crop&w=1200&q=80',
    },
  },
  {
    id: 'mapo-tofu',
    file: path.join(root, 'MindSpace', 'john', 'mapo-tofu.html'),
    meta: {
      tag: '美食专题',
      cover: 'https://images.unsplash.com/photo-1525755662778-989d0529657e?auto=format&fit=crop&w=1200&q=80',
    },
  },
];

function galleryCard({ id, title, subtitle }) {
  return `
    <article class="feed-card">
      <div class="feed-cover"><img src="./${id}-feed.svg" alt="${title} 预览图" /></div>
      <div class="feed-body">
        <h3>${title}</h3>
        <p>${subtitle}</p>
      </div>
    </article>`;
}

async function main() {
  await fs.mkdir(outputDir, { recursive: true });
  const cards = [];

  for (const sample of samples) {
    let html = '';
    try {
      html = await fs.readFile(sample.file, 'utf8');
    } catch {
      console.warn(`跳过缺失样本: ${sample.file}`);
      continue;
    }

    const signals = extractCoverSignals(html, sample.meta);
    const legacySvg = buildThumbnailSvg({
      title: signals.title,
      subtitle: sample.meta.subtitle ?? signals.subtitle,
      accent: signals.accent,
    });
    const coverDataUri = signals.image
      ? await resolveCoverDataUri({
          storageRoot: outputDir,
          contentBaseDir: path.dirname(sample.file),
          imageUrl: signals.image,
        })
      : null;
    const feedSvg = buildFeedThumbnailSvg(signals, { coverDataUri });

    await fs.writeFile(path.join(outputDir, `${sample.id}-legacy.svg`), legacySvg, 'utf8');
    await fs.writeFile(path.join(outputDir, `${sample.id}-feed.svg`), feedSvg, 'utf8');
    await generateHtmlThumbnail(outputDir, `${sample.id}-generated.svg`, html, {
      ...sample.meta,
      contentBaseDir: path.dirname(sample.file),
    });
    cards.push(
      galleryCard({
        id: sample.id,
        title: signals.title,
        subtitle: `${signals.tag} · 新版 3:4 封面`,
      }),
    );
  }

  const html = `<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>MindSpace 预览图 Demo</title>
  <style>
    :root { color-scheme: light; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f4f0e7; color: #18211d; }
    body { margin: 0; padding: 24px; }
    h1 { margin: 0 0 8px; font-size: 28px; }
    .lead { margin: 0 0 24px; color: #5f6963; line-height: 1.6; }
    .compare { display: grid; gap: 28px; }
    .sample { padding: 20px; border-radius: 20px; background: #fff; box-shadow: 0 10px 30px rgba(24,33,29,0.08); }
    .sample h2 { margin: 0 0 16px; font-size: 20px; }
    .pair { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 18px; }
    .thumb { display: grid; gap: 8px; }
    .thumb img { width: 100%; border-radius: 12px; box-shadow: 0 8px 24px rgba(24,33,29,0.12); }
    .thumb span { font-size: 13px; color: #6d7771; }
    .feed-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; max-width: 520px; }
    .feed-card { border: none; border-radius: 12px; overflow: hidden; background: #fff; box-shadow: 0 2px 10px rgba(24,33,29,0.07); }
    .feed-cover { aspect-ratio: 3 / 4; background: #ece7df; }
    .feed-cover img { width: 100%; height: 100%; object-fit: cover; display: block; }
    .feed-body { padding: 10px 12px 12px; }
    .feed-body h3 { margin: 0; font-size: 14px; line-height: 1.45; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
    .feed-body p { margin: 6px 0 0; font-size: 12px; color: #939c97; }
  </style>
</head>
<body>
  <h1>MindSpace 预览图升级 Demo</h1>
  <p class="lead">左侧为旧版横版缩略图，中间为新版 3:4 信息流封面（自动从 HTML 提取标题、配色、emoji），右侧为保存页面时实际写入的 thumbnail.svg。下方是小红书风格卡片效果。</p>
  <div class="compare">
    ${cards
      .map(
        (card, index) => `
    <section class="sample">
      <h2>样本 ${index + 1}</h2>
      <div class="pair">
        <div class="thumb"><img src="./${samples[index].id}-legacy.svg" alt="旧版" /><span>旧版（横版字卡）</span></div>
        <div class="thumb"><img src="./${samples[index].id}-feed.svg" alt="新版" /><span>新版（3:4 精美封面）</span></div>
        <div class="thumb"><img src="./${samples[index].id}-generated.svg" alt="生成结果" /><span>generateHtmlThumbnail 输出</span></div>
      </div>
      <div class="feed-grid" style="margin-top:18px">${card}</div>
    </section>`,
      )
      .join('')}
  </div>
</body>
</html>`;

  await fs.writeFile(path.join(outputDir, 'index.html'), html, 'utf8');
  console.log(`已生成预览页: ${path.join(outputDir, 'index.html')}`);
  console.log('本地查看: http://localhost:5173/thumbnail-demo/');
}

await main();
