import { writeFileSync } from 'node:fs';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { getContextPersistence } from './persistence.mjs';
import { i18n } from './index2.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:process';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:path';
import 'node:os';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import 'better-sqlite3';
import 'node:url';

class L0Cache {
  cache;
  maxEntries;
  maxSize;
  currentSize;
  hits;
  misses;
  constructor(maxEntries, maxSize) {
    this.cache = /* @__PURE__ */ new Map();
    this.maxEntries = maxEntries;
    this.maxSize = maxSize;
    this.currentSize = 0;
    this.hits = 0;
    this.misses = 0;
  }
  get(id) {
    const entry = this.cache.get(id);
    if (!entry) {
      this.misses++;
      return null;
    }
    entry.lastAccessed = Date.now();
    entry.accessCount++;
    this.cache.delete(id);
    this.cache.set(id, entry);
    this.hits++;
    return entry;
  }
  set(id, context) {
    const size = this.estimateSize(context.context);
    while ((this.currentSize + size > this.maxSize || this.cache.size >= this.maxEntries) && this.cache.size > 0) {
      this.evictLRU();
    }
    const existing = this.cache.get(id);
    if (existing) {
      this.currentSize -= this.estimateSize(existing.context);
      this.cache.delete(id);
    }
    this.cache.set(id, context);
    this.currentSize += size;
  }
  has(id) {
    return this.cache.has(id);
  }
  delete(id) {
    const entry = this.cache.get(id);
    if (!entry)
      return false;
    this.currentSize -= this.estimateSize(entry.context);
    return this.cache.delete(id);
  }
  clear() {
    this.cache.clear();
    this.currentSize = 0;
    this.hits = 0;
    this.misses = 0;
  }
  getAll() {
    return Array.from(this.cache.values());
  }
  getStats() {
    const total = this.hits + this.misses;
    return {
      count: this.cache.size,
      size: this.currentSize,
      hitRate: total > 0 ? this.hits / total : 0
    };
  }
  evictLRU() {
    const firstKey = this.cache.keys().next().value;
    if (firstKey) {
      this.delete(firstKey);
    }
  }
  estimateSize(context) {
    let size = context.compressed.length * 2;
    if (context.metadata) {
      size += JSON.stringify(context.metadata).length * 2;
    }
    size += 200;
    return size;
  }
}
class HierarchicalContextLoader {
  persistence;
  projectHash;
  config;
  l0Cache;
  tierMigrations;
  constructor(persistence, projectHash, config) {
    this.persistence = persistence;
    this.projectHash = projectHash;
    this.config = {
      hotThreshold: 24 * 60 * 60 * 1e3,
      // 1 day
      warmThreshold: 7 * 24 * 60 * 60 * 1e3,
      // 7 days
      l0MaxEntries: 100,
      l0MaxSize: 5 * 1024 * 1024,
      // 5MB
      ...config
    };
    this.l0Cache = new L0Cache(this.config.l0MaxEntries, this.config.l0MaxSize);
    this.tierMigrations = {
      hotToWarm: 0,
      warmToCold: 0,
      coldToWarm: 0,
      warmToHot: 0
    };
    this.initializeL0Cache();
  }
  /**
   * Get context by ID (checks all tiers)
   */
  async getContext(contextId) {
    const l0Entry = this.l0Cache.get(contextId);
    if (l0Entry) {
      return l0Entry.context;
    }
    const persisted = this.persistence.getContext(contextId);
    if (!persisted)
      return null;
    const context = this.persistedToCompressed(persisted);
    const tier = this.determineTier(persisted.lastAccessed);
    if (tier === "L0" /* HOT */ || persisted.accessCount > 5) {
      this.promoteToL0(contextId, context, persisted.lastAccessed, persisted.accessCount);
    }
    return context;
  }
  /**
   * Get hot contexts (L0 tier, <1 day)
   */
  getHotContexts() {
    return this.l0Cache.getAll();
  }
  /**
   * Get warm contexts (L1 tier, 1-7 days)
   */
  getWarmContexts(limit) {
    const now = Date.now();
    const warmStart = now - this.config.warmThreshold;
    const warmEnd = now - this.config.hotThreshold;
    const contexts = this.persistence.getProjectContexts(this.projectHash, {
      startTime: warmStart,
      endTime: warmEnd,
      sortBy: "lastAccessed",
      sortOrder: "desc",
      limit
    });
    return contexts.map((p) => this.persistedToTiered(p, "L1" /* WARM */));
  }
  /**
   * Get cold contexts (L2 tier, >7 days)
   */
  getColdContexts(limit) {
    const cutoff = Date.now() - this.config.warmThreshold;
    const contexts = this.persistence.getProjectContexts(this.projectHash, {
      endTime: cutoff,
      sortBy: "lastAccessed",
      sortOrder: "desc",
      limit
    });
    return contexts.map((p) => this.persistedToTiered(p, "L2" /* COLD */));
  }
  /**
   * Get contexts by tier
   */
  getContextsByTier(tier, limit) {
    switch (tier) {
      case "L0" /* HOT */:
        return this.getHotContexts();
      case "L1" /* WARM */:
        return this.getWarmContexts(limit);
      case "L2" /* COLD */:
        return this.getColdContexts(limit);
    }
  }
  /**
   * Lazy load cold contexts (batch loading)
   */
  async lazyColdContexts(offset = 0, limit = 50) {
    const cutoff = Date.now() - this.config.warmThreshold;
    const contexts = this.persistence.queryContexts({
      projectHash: this.projectHash,
      endTime: cutoff,
      sortBy: "lastAccessed",
      sortOrder: "desc",
      limit
    });
    const sliced = contexts.slice(offset, offset + limit);
    return sliced.map((p) => this.persistedToTiered(p, "L2" /* COLD */));
  }
  /**
   * Migrate contexts between tiers based on access patterns
   */
  migrateContexts() {
    const now = Date.now();
    let promoted = 0;
    let demoted = 0;
    const l0Contexts = this.l0Cache.getAll();
    for (const entry of l0Contexts) {
      const age = now - entry.lastAccessed;
      if (age > this.config.hotThreshold) {
        this.l0Cache.delete(entry.id);
        this.tierMigrations.hotToWarm++;
        demoted++;
      }
    }
    const warmContexts = this.getWarmContexts(50);
    for (const entry of warmContexts) {
      if (entry.accessCount > 10) {
        this.promoteToL0(entry.id, entry.context, entry.lastAccessed, entry.accessCount);
        this.tierMigrations.warmToHot++;
        promoted++;
      }
    }
    return { promoted, demoted };
  }
  /**
   * Get tier statistics
   */
  getStats() {
    const l0Stats = this.l0Cache.getStats();
    const now = Date.now();
    const warmStart = now - this.config.warmThreshold;
    const warmEnd = now - this.config.hotThreshold;
    const l1Contexts = this.persistence.queryContexts({
      projectHash: this.projectHash,
      startTime: warmStart,
      endTime: warmEnd
    });
    const l2Contexts = this.persistence.queryContexts({
      projectHash: this.projectHash,
      endTime: warmStart
    });
    return {
      l0: l0Stats,
      l1: {
        count: l1Contexts.length,
        avgAccessTime: this.calculateAvgAccessTime(l1Contexts)
      },
      l2: {
        count: l2Contexts.length,
        avgAccessTime: this.calculateAvgAccessTime(l2Contexts)
      },
      migrations: { ...this.tierMigrations }
    };
  }
  /**
   * Clear L0 cache
   */
  clearL0Cache() {
    this.l0Cache.clear();
  }
  /**
   * Refresh L0 cache with current hot contexts
   */
  refreshL0Cache() {
    this.l0Cache.clear();
    this.initializeL0Cache();
  }
  /**
   * Initialize L0 cache with hot contexts from persistence
   */
  initializeL0Cache() {
    const cutoff = Date.now() - this.config.hotThreshold;
    const hotContexts = this.persistence.getProjectContexts(this.projectHash, {
      startTime: cutoff,
      sortBy: "lastAccessed",
      sortOrder: "desc",
      limit: this.config.l0MaxEntries
    });
    for (const persisted of hotContexts) {
      const context = this.persistedToCompressed(persisted);
      const tiered = {
        id: persisted.id,
        tier: "L0" /* HOT */,
        lastAccessed: persisted.lastAccessed,
        accessCount: persisted.accessCount,
        context
      };
      this.l0Cache.set(persisted.id, tiered);
    }
  }
  /**
   * Promote context to L0 cache
   */
  promoteToL0(id, context, lastAccessed, accessCount) {
    const tiered = {
      id,
      tier: "L0" /* HOT */,
      lastAccessed,
      accessCount,
      context
    };
    this.l0Cache.set(id, tiered);
  }
  /**
   * Determine tier based on last accessed time
   */
  determineTier(lastAccessed) {
    const age = Date.now() - lastAccessed;
    if (age < this.config.hotThreshold) {
      return "L0" /* HOT */;
    } else if (age < this.config.warmThreshold) {
      return "L1" /* WARM */;
    } else {
      return "L2" /* COLD */;
    }
  }
  /**
   * Convert persisted context to compressed context
   */
  persistedToCompressed(persisted) {
    return {
      id: persisted.id,
      compressed: persisted.compressed,
      algorithm: persisted.algorithm,
      strategy: persisted.strategy,
      originalTokens: persisted.originalTokens,
      compressedTokens: persisted.compressedTokens,
      compressionRatio: persisted.compressionRatio,
      metadata: JSON.parse(persisted.metadata),
      compressedAt: persisted.timestamp
    };
  }
  /**
   * Convert persisted context to tiered context
   */
  persistedToTiered(persisted, tier) {
    return {
      id: persisted.id,
      tier,
      lastAccessed: persisted.lastAccessed,
      accessCount: persisted.accessCount,
      context: this.persistedToCompressed(persisted)
    };
  }
  /**
   * Calculate average access time for contexts
   */
  calculateAvgAccessTime(contexts) {
    if (contexts.length === 0)
      return 0;
    const now = Date.now();
    const totalAge = contexts.reduce((sum, c) => sum + (now - c.lastAccessed), 0);
    return totalAge / contexts.length;
  }
}
function createHierarchicalLoader(persistence, projectHash, config) {
  return new HierarchicalContextLoader(persistence, projectHash, config);
}

function formatBytes(bytes) {
  if (bytes === 0)
    return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / k ** i).toFixed(2)} ${sizes[i]}`;
}
function formatDate(timestamp) {
  const date = new Date(timestamp);
  return date.toLocaleString();
}
function formatDuration(ms) {
  const seconds = Math.floor(ms / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  if (days > 0)
    return `${days}d ${hours % 24}h`;
  if (hours > 0)
    return `${hours}h ${minutes % 60}m`;
  if (minutes > 0)
    return `${minutes}m ${seconds % 60}s`;
  return `${seconds}s`;
}
async function listContexts(projectHash) {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4CB} \u5B58\u50A8\u7684\u4E0A\u4E0B\u6587\u5217\u8868" : "\u{1F4CB} Stored Contexts"));
  console.log(a.dim("\u2500".repeat(80)));
  const PAGE_SIZE = 20;
  let offset = 0;
  let showMore = true;
  while (showMore) {
    const contexts = persistence.queryContexts({
      projectHash,
      sortBy: "lastAccessed",
      sortOrder: "desc",
      limit: PAGE_SIZE
    });
    if (contexts.length === 0) {
      console.log(a.yellow(isZh ? "  \u6CA1\u6709\u627E\u5230\u4E0A\u4E0B\u6587" : "  No contexts found"));
      break;
    }
    const displayContexts = contexts.slice(offset, offset + PAGE_SIZE);
    for (const ctx of displayContexts) {
      const age = Date.now() - ctx.lastAccessed;
      const ratio = (ctx.compressionRatio * 100).toFixed(1);
      console.log(`  ${a.green(ctx.id.substring(0, 8))}... ${a.dim("|")} ${a.cyan(ctx.algorithm)} ${a.dim("|")} ${ratio}% ${a.dim("|")} ${a.yellow(ctx.accessCount)} ${isZh ? "\u6B21\u8BBF\u95EE" : "accesses"} ${a.dim("|")} ${formatDuration(age)} ${isZh ? "\u524D" : "ago"}`);
    }
    if (offset + PAGE_SIZE < contexts.length) {
      const { action } = await inquirer.prompt({
        type: "list",
        name: "action",
        message: isZh ? "\u663E\u793A\u66F4\u591A?" : "Show more?",
        choices: [
          { name: isZh ? "\u4E0B\u4E00\u9875" : "Next page", value: "next" },
          { name: isZh ? "\u8FD4\u56DE" : "Back", value: "back" }
        ]
      });
      if (action === "next") {
        offset += PAGE_SIZE;
      } else {
        showMore = false;
      }
    } else {
      showMore = false;
    }
  }
  console.log("");
}
async function searchContexts() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { query } = await inquirer.prompt({
    type: "input",
    name: "query",
    message: isZh ? '\u8F93\u5165\u641C\u7D22\u5173\u952E\u8BCD (\u652F\u6301 AND, OR, NOT, "\u77ED\u8BED"):' : 'Enter search query (supports AND, OR, NOT, "phrases"):',
    validate: (value) => {
      if (!value || value.trim().length === 0) {
        return isZh ? "\u8BF7\u8F93\u5165\u641C\u7D22\u5173\u952E\u8BCD" : "Please enter a search query";
      }
      return true;
    }
  });
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F50D} \u641C\u7D22\u7ED3\u679C" : "\u{1F50D} Search Results"));
  console.log(a.dim("\u2500".repeat(80)));
  const results = persistence.searchContexts(query, {
    sortBy: "relevance",
    sortOrder: "desc",
    limit: 50
  });
  if (results.length === 0) {
    console.log(a.yellow(isZh ? "  \u6CA1\u6709\u627E\u5230\u5339\u914D\u7684\u4E0A\u4E0B\u6587" : "  No matching contexts found"));
  } else {
    for (const result of results) {
      const ratio = (result.compressionRatio * 100).toFixed(1);
      console.log(`  ${a.green(result.id.substring(0, 8))}... ${a.dim("|")} ${a.cyan(result.algorithm)} ${a.dim("|")} ${ratio}% ${a.dim("|")} ${a.magenta(`rank: ${result.rank.toFixed(2)}`)}`);
      if (result.snippet) {
        console.log(`    ${a.dim(result.snippet.replace(/<mark>/g, a.yellow.open).replace(/<\/mark>/g, a.yellow.close))}`);
      }
    }
  }
  console.log("");
}
async function viewContextDetails() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { contextId } = await inquirer.prompt({
    type: "input",
    name: "contextId",
    message: isZh ? "\u8F93\u5165\u4E0A\u4E0B\u6587 ID (\u5B8C\u6574\u6216\u524D\u7F00):" : "Enter context ID (full or prefix):",
    validate: (value) => {
      if (!value || value.trim().length === 0) {
        return isZh ? "\u8BF7\u8F93\u5165\u4E0A\u4E0B\u6587 ID" : "Please enter a context ID";
      }
      return true;
    }
  });
  const allContexts = persistence.queryContexts({ limit: 1e4 });
  const context = allContexts.find((c) => c.id.startsWith(contextId.trim()));
  if (!context) {
    console.log(a.red(isZh ? "  \u672A\u627E\u5230\u4E0A\u4E0B\u6587" : "  Context not found"));
    return;
  }
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4C4} \u4E0A\u4E0B\u6587\u8BE6\u60C5" : "\u{1F4C4} Context Details"));
  console.log(a.dim("\u2500".repeat(80)));
  console.log(`  ${a.bold("ID:")} ${context.id}`);
  console.log(`  ${a.bold(isZh ? "\u9879\u76EE:" : "Project:")} ${context.projectHash}`);
  console.log(`  ${a.bold(isZh ? "\u7B97\u6CD5:" : "Algorithm:")} ${context.algorithm}`);
  console.log(`  ${a.bold(isZh ? "\u7B56\u7565:" : "Strategy:")} ${context.strategy}`);
  console.log(`  ${a.bold(isZh ? "\u539F\u59CB Tokens:" : "Original Tokens:")} ${context.originalTokens.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u538B\u7F29\u540E Tokens:" : "Compressed Tokens:")} ${context.compressedTokens.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u538B\u7F29\u7387:" : "Compression Ratio:")} ${(context.compressionRatio * 100).toFixed(1)}%`);
  console.log(`  ${a.bold(isZh ? "\u8BBF\u95EE\u6B21\u6570:" : "Access Count:")} ${context.accessCount}`);
  console.log(`  ${a.bold(isZh ? "\u521B\u5EFA\u65F6\u95F4:" : "Created:")} ${formatDate(context.timestamp)}`);
  console.log(`  ${a.bold(isZh ? "\u6700\u540E\u8BBF\u95EE:" : "Last Accessed:")} ${formatDate(context.lastAccessed)}`);
  try {
    const metadata = JSON.parse(context.metadata);
    if (Object.keys(metadata).length > 0) {
      console.log(`  ${a.bold(isZh ? "\u5143\u6570\u636E:" : "Metadata:")}`);
      for (const [key, value] of Object.entries(metadata)) {
        console.log(`    ${a.cyan(key)}: ${JSON.stringify(value)}`);
      }
    }
  } catch {
  }
  console.log("");
}
async function exportContexts() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { projectHash } = await inquirer.prompt({
    type: "input",
    name: "projectHash",
    message: isZh ? "\u8F93\u5165\u9879\u76EE\u54C8\u5E0C (\u7559\u7A7A\u5BFC\u51FA\u5168\u90E8):" : "Enter project hash (leave empty for all):"
  });
  const { outputPath } = await inquirer.prompt({
    type: "input",
    name: "outputPath",
    message: isZh ? "\u8F93\u51FA\u6587\u4EF6\u8DEF\u5F84:" : "Output file path:",
    default: join(process.cwd(), "contexts-export.json")
  });
  const contexts = persistence.exportContexts(projectHash || void 0);
  writeFileSync(outputPath, JSON.stringify(contexts, null, 2), "utf-8");
  console.log("");
  console.log(a.green(`\u2714 ${isZh ? "\u5DF2\u5BFC\u51FA" : "Exported"} ${contexts.length} ${isZh ? "\u4E2A\u4E0A\u4E0B\u6587\u5230" : "contexts to"} ${outputPath}`));
  console.log("");
}
async function importContexts() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { inputPath } = await inquirer.prompt({
    type: "input",
    name: "inputPath",
    message: isZh ? "\u8F93\u5165\u6587\u4EF6\u8DEF\u5F84:" : "Input file path:",
    validate: (value) => {
      if (!value || value.trim().length === 0) {
        return isZh ? "\u8BF7\u8F93\u5165\u6587\u4EF6\u8DEF\u5F84" : "Please enter a file path";
      }
      return true;
    }
  });
  try {
    const fs = require("node:fs");
    const content = fs.readFileSync(inputPath, "utf-8");
    const contexts = JSON.parse(content);
    const imported = persistence.importContexts(contexts);
    console.log("");
    console.log(a.green(`\u2714 ${isZh ? "\u5DF2\u5BFC\u5165" : "Imported"} ${imported} ${isZh ? "\u4E2A\u4E0A\u4E0B\u6587" : "contexts"}`));
    console.log("");
  } catch (error) {
    console.log("");
    console.log(a.red(`\u2716 ${isZh ? "\u5BFC\u5165\u5931\u8D25:" : "Import failed:"} ${error instanceof Error ? error.message : String(error)}`));
    console.log("");
  }
}
async function clearOldContexts() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { ageChoice } = await inquirer.prompt({
    type: "list",
    name: "ageChoice",
    message: isZh ? "\u6E05\u7406\u591A\u4E45\u4E4B\u524D\u7684\u4E0A\u4E0B\u6587?" : "Clear contexts older than:",
    choices: [
      { name: isZh ? "7 \u5929" : "7 days", value: "7" },
      { name: isZh ? "30 \u5929" : "30 days", value: "30" },
      { name: isZh ? "90 \u5929" : "90 days", value: "90" },
      { name: isZh ? "180 \u5929" : "180 days", value: "180" },
      { name: isZh ? "\u81EA\u5B9A\u4E49" : "Custom", value: "custom" }
    ]
  });
  let days;
  if (ageChoice === "custom") {
    const { customDays } = await inquirer.prompt({
      type: "input",
      name: "customDays",
      message: isZh ? "\u8F93\u5165\u5929\u6570:" : "Enter days:",
      validate: (value) => {
        const num = parseInt(value, 10);
        if (isNaN(num) || num <= 0) {
          return isZh ? "\u8BF7\u8F93\u5165\u6709\u6548\u7684\u5929\u6570" : "Please enter a valid number of days";
        }
        return true;
      }
    });
    days = parseInt(customDays, 10);
  } else {
    days = parseInt(ageChoice, 10);
  }
  const maxAge = days * 24 * 60 * 60 * 1e3;
  const { confirm } = await inquirer.prompt({
    type: "confirm",
    name: "confirm",
    message: isZh ? `\u786E\u8BA4\u6E05\u7406 ${days} \u5929\u524D\u7684\u4E0A\u4E0B\u6587?` : `Confirm clearing contexts older than ${days} days?`,
    default: false
  });
  if (!confirm) {
    console.log(a.yellow(isZh ? "  \u5DF2\u53D6\u6D88" : "  Cancelled"));
    return;
  }
  const deleted = persistence.cleanup(maxAge);
  console.log("");
  console.log(a.green(`\u2714 ${isZh ? "\u5DF2\u6E05\u7406" : "Cleared"} ${deleted} ${isZh ? "\u4E2A\u4E0A\u4E0B\u6587" : "contexts"}`));
  console.log("");
}
async function viewTierDistribution() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { projectHash } = await inquirer.prompt({
    type: "input",
    name: "projectHash",
    message: isZh ? "\u8F93\u5165\u9879\u76EE\u54C8\u5E0C (\u7559\u7A7A\u67E5\u770B\u5168\u90E8):" : "Enter project hash (leave empty for all):"
  });
  const loader = createHierarchicalLoader(
    persistence,
    projectHash || "global"
  );
  const stats = loader.getStats();
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4CA} \u5C42\u7EA7\u5206\u5E03\u7EDF\u8BA1" : "\u{1F4CA} Tier Distribution"));
  console.log(a.dim("\u2500".repeat(80)));
  console.log(`  ${a.bold.red("L0 (Hot)")} ${a.dim("- <1 day, in-memory cache")}`);
  console.log(`    ${a.cyan(isZh ? "\u6570\u91CF:" : "Count:")} ${stats.l0.count}`);
  console.log(`    ${a.cyan(isZh ? "\u5927\u5C0F:" : "Size:")} ${formatBytes(stats.l0.size)}`);
  console.log(`    ${a.cyan(isZh ? "\u547D\u4E2D\u7387:" : "Hit Rate:")} ${(stats.l0.hitRate * 100).toFixed(1)}%`);
  console.log(`  ${a.bold.yellow("L1 (Warm)")} ${a.dim("- 1-7 days, indexed in DB")}`);
  console.log(`    ${a.cyan(isZh ? "\u6570\u91CF:" : "Count:")} ${stats.l1.count}`);
  console.log(`    ${a.cyan(isZh ? "\u5E73\u5747\u8BBF\u95EE\u65F6\u95F4:" : "Avg Access Time:")} ${formatDuration(stats.l1.avgAccessTime)}`);
  console.log(`  ${a.bold.blue("L2 (Cold)")} ${a.dim("- >7 days, lazy-loaded")}`);
  console.log(`    ${a.cyan(isZh ? "\u6570\u91CF:" : "Count:")} ${stats.l2.count}`);
  console.log(`    ${a.cyan(isZh ? "\u5E73\u5747\u8BBF\u95EE\u65F6\u95F4:" : "Avg Access Time:")} ${formatDuration(stats.l2.avgAccessTime)}`);
  console.log(`  ${a.bold.magenta(isZh ? "\u5C42\u7EA7\u8FC1\u79FB:" : "Tier Migrations:")}`);
  console.log(`    ${a.dim("Hot \u2192 Warm:")} ${stats.migrations.hotToWarm}`);
  console.log(`    ${a.dim("Warm \u2192 Cold:")} ${stats.migrations.warmToCold}`);
  console.log(`    ${a.dim("Cold \u2192 Warm:")} ${stats.migrations.coldToWarm}`);
  console.log(`    ${a.dim("Warm \u2192 Hot:")} ${stats.migrations.warmToHot}`);
  console.log("");
}
async function migrateTiers() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { projectHash } = await inquirer.prompt({
    type: "input",
    name: "projectHash",
    message: isZh ? "\u8F93\u5165\u9879\u76EE\u54C8\u5E0C (\u7559\u7A7A\u8FC1\u79FB\u5168\u90E8):" : "Enter project hash (leave empty for all):"
  });
  const loader = createHierarchicalLoader(
    persistence,
    projectHash || "global"
  );
  console.log("");
  console.log(a.cyan(isZh ? "\u6B63\u5728\u8FC1\u79FB\u5C42\u7EA7..." : "Migrating tiers..."));
  const result = loader.migrateContexts();
  console.log("");
  console.log(a.green(`\u2714 ${isZh ? "\u8FC1\u79FB\u5B8C\u6210" : "Migration complete"}`));
  console.log(`  ${a.cyan(isZh ? "\u63D0\u5347:" : "Promoted:")} ${result.promoted}`);
  console.log(`  ${a.cyan(isZh ? "\u964D\u7EA7:" : "Demoted:")} ${result.demoted}`);
  console.log("");
}
async function viewDatabaseStats() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const stats = persistence.getStats();
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4C8} \u6570\u636E\u5E93\u7EDF\u8BA1" : "\u{1F4C8} Database Statistics"));
  console.log(a.dim("\u2500".repeat(80)));
  console.log(`  ${a.bold(isZh ? "\u603B\u4E0A\u4E0B\u6587\u6570:" : "Total Contexts:")} ${stats.totalContexts.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u603B\u9879\u76EE\u6570:" : "Total Projects:")} ${stats.totalProjects.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u539F\u59CB Tokens:" : "Original Tokens:")} ${stats.totalOriginalTokens.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u538B\u7F29\u540E Tokens:" : "Compressed Tokens:")} ${stats.totalCompressedTokens.toLocaleString()}`);
  console.log(`  ${a.bold(isZh ? "\u5E73\u5747\u538B\u7F29\u7387:" : "Avg Compression:")} ${(stats.averageCompressionRatio * 100).toFixed(1)}%`);
  console.log(`  ${a.bold(isZh ? "\u6570\u636E\u5E93\u5927\u5C0F:" : "Database Size:")} ${formatBytes(stats.totalSize)}`);
  if (stats.oldestContext) {
    console.log(`  ${a.bold(isZh ? "\u6700\u65E9\u4E0A\u4E0B\u6587:" : "Oldest Context:")} ${formatDate(stats.oldestContext)}`);
  }
  if (stats.newestContext) {
    console.log(`  ${a.bold(isZh ? "\u6700\u65B0\u4E0A\u4E0B\u6587:" : "Newest Context:")} ${formatDate(stats.newestContext)}`);
  }
  const saved = stats.totalOriginalTokens - stats.totalCompressedTokens;
  console.log(`  ${a.bold.green(isZh ? "\u8282\u7701 Tokens:" : "Tokens Saved:")} ${saved.toLocaleString()} (${(stats.averageCompressionRatio * 100).toFixed(1)}%)`);
  console.log("");
}
async function vacuumDatabase() {
  const isZh = i18n.language === "zh-CN";
  const persistence = getContextPersistence();
  const { confirm } = await inquirer.prompt({
    type: "confirm",
    name: "confirm",
    message: isZh ? "\u786E\u8BA4\u538B\u7F29\u6570\u636E\u5E93? (\u8FD9\u53EF\u80FD\u9700\u8981\u4E00\u4E9B\u65F6\u95F4)" : "Confirm vacuum database? (This may take some time)",
    default: false
  });
  if (!confirm) {
    console.log(a.yellow(isZh ? "  \u5DF2\u53D6\u6D88" : "  Cancelled"));
    return;
  }
  console.log("");
  console.log(a.cyan(isZh ? "\u6B63\u5728\u538B\u7F29\u6570\u636E\u5E93..." : "Vacuuming database..."));
  persistence.vacuum();
  console.log("");
  console.log(a.green(`\u2714 ${isZh ? "\u6570\u636E\u5E93\u538B\u7F29\u5B8C\u6210" : "Database vacuum complete"}`));
  console.log("");
}
async function showPersistenceMenu() {
  const isZh = i18n.language === "zh-CN";
  console.log("");
  console.log(a.bold.yellow(isZh ? "\u{1F4BE} \u6301\u4E45\u5316\u7BA1\u7406\u5668" : "\u{1F4BE} Persistence Manager"));
  console.log(a.dim("\u2500".repeat(80)));
  console.log(`  ${a.green("1.")} ${isZh ? "\u5217\u51FA\u5B58\u50A8\u7684\u4E0A\u4E0B\u6587" : "List stored contexts"} ${a.dim(isZh ? "- \u5206\u9875\u663E\u793A\u6240\u6709\u4E0A\u4E0B\u6587" : "- Paginated view of all contexts")}`);
  console.log(`  ${a.green("2.")} ${isZh ? "\u641C\u7D22\u4E0A\u4E0B\u6587" : "Search contexts"} ${a.dim(isZh ? "- \u5168\u6587\u641C\u7D22 (FTS5)" : "- Full-text search (FTS5)")}`);
  console.log(`  ${a.green("3.")} ${isZh ? "\u67E5\u770B\u4E0A\u4E0B\u6587\u8BE6\u60C5" : "View context details"} ${a.dim(isZh ? "- \u663E\u793A\u5143\u6570\u636E\u548C\u7EDF\u8BA1" : "- Show metadata and stats")}`);
  console.log(`  ${a.green("4.")} ${isZh ? "\u5BFC\u51FA\u4E0A\u4E0B\u6587" : "Export contexts"} ${a.dim(isZh ? "- \u5BFC\u51FA\u4E3A JSON \u683C\u5F0F" : "- Export to JSON format")}`);
  console.log(`  ${a.green("5.")} ${isZh ? "\u5BFC\u5165\u4E0A\u4E0B\u6587" : "Import contexts"} ${a.dim(isZh ? "- \u4ECE JSON \u5BFC\u5165" : "- Import from JSON")}`);
  console.log(`  ${a.green("6.")} ${isZh ? "\u6E05\u7406\u65E7\u4E0A\u4E0B\u6587" : "Clear old contexts"} ${a.dim(isZh ? "- \u6309\u65F6\u95F4\u6E05\u7406" : "- Clear by age")}`);
  console.log(`  ${a.green("7.")} ${isZh ? "\u67E5\u770B\u5C42\u7EA7\u5206\u5E03" : "View tier distribution"} ${a.dim(isZh ? "- L0/L1/L2 \u7EDF\u8BA1" : "- L0/L1/L2 stats")}`);
  console.log(`  ${a.green("8.")} ${isZh ? "\u624B\u52A8\u8FC1\u79FB\u5C42\u7EA7" : "Migrate tiers manually"} ${a.dim(isZh ? "- \u4F18\u5316\u5C42\u7EA7\u5206\u5E03" : "- Optimize tier distribution")}`);
  console.log(`  ${a.green("9.")} ${isZh ? "\u6570\u636E\u5E93\u7EDF\u8BA1" : "Database statistics"} ${a.dim(isZh ? "- \u67E5\u770B\u5168\u5C40\u7EDF\u8BA1" : "- View global stats")}`);
  console.log(`  ${a.green("V.")} ${isZh ? "\u538B\u7F29\u6570\u636E\u5E93" : "Vacuum database"} ${a.dim(isZh ? "- \u56DE\u6536\u7A7A\u95F4" : "- Reclaim space")}`);
  console.log(`  ${a.green("Q.")} ${isZh ? "\u8FD4\u56DE" : "Back"}`);
  console.log("");
  const { choice } = await inquirer.prompt({
    type: "input",
    name: "choice",
    message: isZh ? "\u8BF7\u9009\u62E9\u64CD\u4F5C:" : "Select operation:",
    validate: (value) => {
      const normalized2 = value.trim().toLowerCase();
      const valid = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "v", "q"];
      return valid.includes(normalized2) || (isZh ? "\u8BF7\u8F93\u5165\u6709\u6548\u9009\u9879" : "Please enter a valid option");
    }
  });
  const normalized = choice.trim().toLowerCase();
  switch (normalized) {
    case "1":
      await listContexts();
      break;
    case "2":
      await searchContexts();
      break;
    case "3":
      await viewContextDetails();
      break;
    case "4":
      await exportContexts();
      break;
    case "5":
      await importContexts();
      break;
    case "6":
      await clearOldContexts();
      break;
    case "7":
      await viewTierDistribution();
      break;
    case "8":
      await migrateTiers();
      break;
    case "9":
      await viewDatabaseStats();
      break;
    case "v":
      await vacuumDatabase();
      break;
    case "q":
      return false;
  }
  return true;
}
async function persistenceManager() {
  try {
    let continueMenu = true;
    while (continueMenu) {
      continueMenu = await showPersistenceMenu();
    }
  } catch (error) {
    const isZh = i18n.language === "zh-CN";
    console.error(a.red(`${isZh ? "\u9519\u8BEF:" : "Error:"} ${error instanceof Error ? error.message : String(error)}`));
  }
}

export { persistenceManager };
