/**
 * LiteMall 静态页面缓存
 * 
 * 爬虫访问时，SSR渲染的页面自动缓存为HTML文件
 * 下次同爬虫访问直接返回文件，0数据库查询
 * 大幅减少SQLite读压力
 */

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const CACHE_DIR = path.join(__dirname, '..', '..', 'cache', 'pages');
const CACHE_TTL = 24 * 60 * 60 * 1000; // 24小时过期
const MAX_CACHED_PAGES = 200;            // 最多缓存200页

// 确保缓存目录存在
if (!fs.existsSync(CACHE_DIR)) {
  fs.mkdirSync(CACHE_DIR, { recursive: true });
}

/**
 * 生成缓存文件名（基于URL+UA摘要）
 */
    // NOTE: 边界：url 为 null/undefined 时 update() 会抛异常; userAgent 已通过 || '' 兜底

function getCacheKey(url, userAgent) {
  const isCrawler = /bot|crawl|spider|slurp|fetch|seo/i.test(userAgent || '');
  if (!isCrawler) return null; // 非爬虫不缓存
  
  const hash = crypto.createHash('md5').update(url).digest('hex');
  return `${hash}.html`;
}

/**
 * 写入缓存
 */
function set(url, userAgent, html) {
  const key = getCacheKey(url, userAgent);
  if (!key) return false;
}

/**
 * 读取缓存
 */
function get(url, userAgent) {
  const key = getCacheKey(url, userAgent);
  if (!key) return null;
  
  try {
    const filePath = path.join(CACHE_DIR, key);
    if (!fs.existsSync(filePath)) return null;
    
    const stat = fs.statSync(filePath);
    if (Date.now() - stat.mtimeMs > CACHE_TTL) {
      fs.unlinkSync(filePath); // 过期删除
      return null;
    }
    
    return fs.readFileSync(filePath, 'utf-8');
  } catch (e) {
    return null;
  }
}

/**
 * 清理过期+超量缓存
 */
function cleanup() {
  try {
    const files = fs.readdirSync(CACHE_DIR)
      .map(f => ({ name: f, path: path.join(CACHE_DIR, f), mtime: fs.statSync(path.join(CACHE_DIR, f)).mtimeMs }))
      .sort((a, b) => a.mtime - b.mtime);
    
    // 删除过期
    const now = Date.now();
    files.filter(f => now - f.mtime > CACHE_TTL).forEach(f => {
      fs.unlinkSync(f.path);
    });
    
    // 如果超过上限，删除最旧的
    const remaining = fs.readdirSync(CACHE_DIR);
    if (remaining.length > MAX_CACHED_PAGES) {
      const toDelete = remaining
        .map(f => ({ name: f, path: path.join(CACHE_DIR, f), mtime: fs.statSync(path.join(CACHE_DIR, f)).mtimeMs }))
        .sort((a, b) => a.mtime - b.mtime)
        .slice(0, remaining.length - MAX_CACHED_PAGES);
      toDelete.forEach(f => fs.unlinkSync(f.path));
    }
  } catch (e) { /* 静默 */ }
}

/**
 * 清空所有缓存（商品更新时调用）
 */
function flush() {
}

module.exports = { get, set, flush, cleanup, CACHE_DIR };
