import { SESSION_KEY_PREFIX, isHistoryKey } from "./session-storage.js";
import { escapeHtml, formatBytes } from "../utils.js";

export async function getStorageStats() {
  const allStored = await chrome.storage.local.get(null);
  const keys = Object.keys(allStored);
  const historyKeys = keys.filter(isHistoryKey);
  const settingsKeys = keys.filter((key) => key.toLowerCase().includes("settings"));

  return {
    totalBytes: await chrome.storage.local.getBytesInUse(null),
    historyCount: historyKeys.length,
    historyBytes: historyKeys.length ? await chrome.storage.local.getBytesInUse(historyKeys) : 0,
    settingsBytes: settingsKeys.length ? await chrome.storage.local.getBytesInUse(settingsKeys) : 0,
    otherBytes: Math.max(
      0,
      (await chrome.storage.local.getBytesInUse(null)) -
        (historyKeys.length ? await chrome.storage.local.getBytesInUse(historyKeys) : 0) -
        (settingsKeys.length ? await chrome.storage.local.getBytesInUse(settingsKeys) : 0)
    )
  };
}

export function buildStorageBreakdownHtml(stats) {
  const items = [
    {
      name: "页面会话",
      desc: `${stats.historyCount} 个页面的聊天记录与上下文摘要`,
      size: formatBytes(stats.historyBytes)
    },
    {
      name: "设置",
      desc: "API Key、模型、字体、默认开关等配置",
      size: formatBytes(stats.settingsBytes)
    },
    {
      name: "其他",
      desc: "当前扩展在本地存储里的其他键值",
      size: formatBytes(stats.otherBytes)
    }
  ];

  return items
    .map(
      (item) => `
      <div class="panel-storage-item">
        <div>
          <div class="panel-storage-item-name">${escapeHtml(item.name)}</div>
          <div class="panel-storage-item-desc">${escapeHtml(item.desc)}</div>
        </div>
        <div class="panel-storage-item-size">${escapeHtml(item.size)}</div>
      </div>
    `
    )
    .join("");
}

export async function getStorageInventory() {
  const allStored = await chrome.storage.local.get(null);
  const keys = Object.keys(allStored).sort();
  const historyKeys = keys.filter(isHistoryKey);
  const settingsKeys = keys.filter((key) => key.toLowerCase().includes("settings"));
  const otherKeys = keys.filter((key) => !historyKeys.includes(key) && !settingsKeys.includes(key));

  return {
    totalKeys: keys.length,
    historyKeys,
    settingsKeys,
    otherKeys
  };
}
