#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadH5Environment } from './load-env.mjs';
import { createDbPool } from '../db.mjs';
import {
  ensureHtmlThumbnail,
  pageThumbnailKey,
  assetThumbnailKey,
} from '../mindspace-thumbnails.mjs';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
loadH5Environment(path.dirname(fileURLToPath(import.meta.url)));

const storageRoot = process.env.MINDSPACE_STORAGE_ROOT
  ? path.resolve(process.env.MINDSPACE_STORAGE_ROOT)
  : path.join(root, 'data', 'mindspace');

async function rebuildPageThumbnails(pool) {
  const [rows] = await pool.query(
    `SELECT p.id AS page_id, p.user_id, p.title, p.summary, p.page_type, pv.version_no, av.storage_key
     FROM h5_page_records p
     JOIN h5_page_versions pv ON pv.id = p.current_version_id
     JOIN h5_asset_versions av ON av.asset_id = pv.content_asset_id AND av.version_no = 1
     WHERE p.status <> 'deleted' AND p.page_type = 'html'`,
  );
  let rebuilt = 0;
  for (const row of rows) {
    const content = await fs.readFile(path.join(storageRoot, row.storage_key), 'utf8');
    await ensureHtmlThumbnail(storageRoot, pageThumbnailKey(row.user_id, row.page_id), content, {
      title: row.title,
      subtitle: row.summary || `草稿 v${row.version_no}`,
      tag: '网页',
      contentStorageKey: row.storage_key,
    });
    rebuilt += 1;
  }
  return rebuilt;
}

async function rebuildAssetThumbnails(pool) {
  const [rows] = await pool.query(
    `SELECT a.id AS asset_id, a.user_id, a.display_name, c.category_code, av.storage_key
     FROM h5_assets a
     JOIN h5_space_categories c ON c.id = a.category_id
     JOIN h5_asset_versions av ON av.asset_id = a.id AND av.version_no = 1
     WHERE a.status <> 'deleted' AND a.mime_type = 'text/html'`,
  );
  let rebuilt = 0;
  for (const row of rows) {
    const content = await fs.readFile(path.join(storageRoot, row.storage_key), 'utf8');
    await ensureHtmlThumbnail(storageRoot, assetThumbnailKey(row.user_id, row.asset_id), content, {
      title: row.display_name,
      subtitle: String(row.category_code ?? 'HTML').toUpperCase(),
      contentStorageKey: row.storage_key,
    });
    rebuilt += 1;
  }
  return rebuilt;
}

const pool = createDbPool();
try {
  const pages = await rebuildPageThumbnails(pool);
  const assets = await rebuildAssetThumbnails(pool);
  console.log(`已重建缩略图：${pages} 个页面，${assets} 个 HTML 资产`);
} finally {
  await pool.end();
}
