import { existsSync } from 'node:fs';
import { mkdir, writeFile, readFile, readdir, rm, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join as join$1 } from 'node:path';
import process__default from 'node:process';
import a from './index5.mjs';
import { i as inquirer } from './index6.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:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:crypto';
import 'buffer';
import 'string_decoder';

class SessionManager {
  sessionsDir;
  autoCleanupDays;
  constructor(options = {}) {
    this.sessionsDir = options.sessionsDir || join(homedir(), ".ccjk", "sessions");
    this.autoCleanupDays = options.autoCleanupDays || 30;
  }
  /**
   * Initialize sessions directory
   */
  async ensureSessionsDir() {
    if (!existsSync(this.sessionsDir)) {
      await mkdir(this.sessionsDir, { recursive: true });
    }
  }
  /**
   * Generate unique session ID
   */
  generateSessionId() {
    return `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
  }
  /**
   * Get session file path
   */
  getSessionPath(sessionId) {
    return join(this.sessionsDir, `${sessionId}.json`);
  }
  /**
   * Create a new session
   */
  async createSession(name, provider, apiKey, options) {
    await this.ensureSessionsDir();
    const session = {
      id: this.generateSessionId(),
      name,
      provider,
      apiKey,
      apiUrl: options?.apiUrl,
      model: options?.model,
      codeType: options?.codeType,
      createdAt: /* @__PURE__ */ new Date(),
      lastUsedAt: /* @__PURE__ */ new Date(),
      history: [],
      metadata: options?.metadata
    };
    await this.saveSession(session);
    return session;
  }
  /**
   * Save session to storage
   */
  async saveSession(session) {
    await this.ensureSessionsDir();
    const sessionPath = this.getSessionPath(session.id);
    const sessionData = {
      ...session,
      createdAt: session.createdAt.toISOString(),
      lastUsedAt: session.lastUsedAt.toISOString(),
      history: session.history.map((entry) => ({
        ...entry,
        timestamp: entry.timestamp.toISOString()
      }))
    };
    await writeFile(sessionPath, JSON.stringify(sessionData, null, 2), "utf-8");
  }
  /**
   * Load session by ID or name
   */
  async loadSession(nameOrId) {
    await this.ensureSessionsDir();
    let sessionPath = this.getSessionPath(nameOrId);
    if (!existsSync(sessionPath)) {
      const sessions = await this.listSessions();
      const found = sessions.find((s) => s.name === nameOrId);
      if (!found) {
        return null;
      }
      sessionPath = this.getSessionPath(found.id);
    }
    try {
      const content = await readFile(sessionPath, "utf-8");
      const data = JSON.parse(content);
      return {
        ...data,
        createdAt: new Date(data.createdAt),
        lastUsedAt: new Date(data.lastUsedAt),
        history: data.history.map((entry) => ({
          ...entry,
          timestamp: new Date(entry.timestamp)
        }))
      };
    } catch (error) {
      console.error(`Failed to load session ${nameOrId}:`, error);
      return null;
    }
  }
  /**
   * List all sessions
   */
  async listSessions(options = {}) {
    await this.ensureSessionsDir();
    try {
      const files = await readdir(this.sessionsDir);
      const sessionFiles = files.filter((f) => f.endsWith(".json"));
      const sessions = [];
      for (const file of sessionFiles) {
        const sessionPath = join(this.sessionsDir, file);
        try {
          const content = await readFile(sessionPath, "utf-8");
          const data = JSON.parse(content);
          sessions.push({
            ...data,
            createdAt: new Date(data.createdAt),
            lastUsedAt: new Date(data.lastUsedAt),
            history: data.history.map((entry) => ({
              ...entry,
              timestamp: new Date(entry.timestamp)
            }))
          });
        } catch (error) {
          console.error(`Failed to load session file ${file}:`, error);
        }
      }
      const sortBy = options.sortBy || "lastUsedAt";
      const order = options.order || "desc";
      sessions.sort((a, b) => {
        let comparison = 0;
        if (sortBy === "name") {
          comparison = (a.name || a.id).localeCompare(b.name || b.id);
        } else if (sortBy === "createdAt") {
          comparison = a.createdAt.getTime() - b.createdAt.getTime();
        } else if (sortBy === "lastUsedAt") {
          comparison = a.lastUsedAt.getTime() - b.lastUsedAt.getTime();
        }
        return order === "asc" ? comparison : -comparison;
      });
      if (options.limit && options.limit > 0) {
        return sessions.slice(0, options.limit);
      }
      return sessions;
    } catch (error) {
      console.error("Failed to list sessions:", error);
      return [];
    }
  }
  /**
   * Delete session by ID or name
   */
  async deleteSession(nameOrId) {
    const session = await this.loadSession(nameOrId);
    if (!session) {
      return false;
    }
    const sessionPath = this.getSessionPath(session.id);
    try {
      const fs = await import('node:fs/promises');
      await fs.unlink(sessionPath);
      return true;
    } catch (error) {
      console.error(`Failed to delete session ${nameOrId}:`, error);
      return false;
    }
  }
  /**
   * Rename session
   */
  async renameSession(oldName, newName) {
    const session = await this.loadSession(oldName);
    if (!session) {
      return false;
    }
    session.name = newName;
    session.lastUsedAt = /* @__PURE__ */ new Date();
    await this.saveSession(session);
    return true;
  }
  /**
   * Add history entry to session
   */
  async addHistoryEntry(sessionId, role, content, tokens) {
    const session = await this.loadSession(sessionId);
    if (!session) {
      return false;
    }
    session.history.push({
      timestamp: /* @__PURE__ */ new Date(),
      role,
      content,
      tokens
    });
    session.lastUsedAt = /* @__PURE__ */ new Date();
    await this.saveSession(session);
    return true;
  }
  /**
   * Update session metadata
   */
  async updateSession(sessionId, updates) {
    const session = await this.loadSession(sessionId);
    if (!session) {
      return false;
    }
    Object.assign(session, updates);
    session.lastUsedAt = /* @__PURE__ */ new Date();
    await this.saveSession(session);
    return true;
  }
  /**
   * Clean up old sessions (older than autoCleanupDays)
   */
  async cleanupOldSessions() {
    const sessions = await this.listSessions();
    const cutoffDate = /* @__PURE__ */ new Date();
    cutoffDate.setDate(cutoffDate.getDate() - this.autoCleanupDays);
    let deletedCount = 0;
    for (const session of sessions) {
      if (session.lastUsedAt < cutoffDate) {
        const deleted = await this.deleteSession(session.id);
        if (deleted) {
          deletedCount++;
        }
      }
    }
    return deletedCount;
  }
  /**
   * Get session statistics
   */
  async getStatistics() {
    const sessions = await this.listSessions();
    if (sessions.length === 0) {
      return {
        totalSessions: 0,
        totalHistoryEntries: 0
      };
    }
    const totalHistoryEntries = sessions.reduce((sum, s) => sum + s.history.length, 0);
    const sortedByCreated = [...sessions].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
    const sortedByUsed = [...sessions].sort((a, b) => b.lastUsedAt.getTime() - a.lastUsedAt.getTime());
    return {
      totalSessions: sessions.length,
      totalHistoryEntries,
      oldestSession: sortedByCreated[0]?.createdAt,
      newestSession: sortedByCreated[sortedByCreated.length - 1]?.createdAt,
      mostRecentlyUsed: sortedByUsed[0]?.lastUsedAt
    };
  }
  /**
   * Export session to JSON
   */
  async exportSession(sessionId) {
    const session = await this.loadSession(sessionId);
    if (!session) {
      return null;
    }
    return JSON.stringify(session, null, 2);
  }
  /**
   * Import session from JSON
   */
  async importSession(jsonData) {
    try {
      const data = JSON.parse(jsonData);
      const session = {
        ...data,
        id: this.generateSessionId(),
        createdAt: new Date(data.createdAt),
        lastUsedAt: /* @__PURE__ */ new Date(),
        history: data.history.map((entry) => ({
          ...entry,
          timestamp: new Date(entry.timestamp)
        }))
      };
      await this.saveSession(session);
      return session;
    } catch (error) {
      console.error("Failed to import session:", error);
      return null;
    }
  }
}
let sessionManagerInstance = null;
function getSessionManager(options) {
  if (!sessionManagerInstance) {
    sessionManagerInstance = new SessionManager(options);
  }
  return sessionManagerInstance;
}

const SESSIONS_DIR = join$1(homedir(), ".ccjk", "sessions");
const CCJK_DIR = join$1(homedir(), ".ccjk");
const CLAUDE_DIR = join$1(homedir(), ".claude");
async function saveSession() {
  try {
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    const sessionId = `session-${Date.now()}`;
    const { description } = await inquirer.prompt({
      type: "input",
      name: "description",
      message: "Session description (optional):"
    });
    const metadata = {
      id: sessionId,
      timestamp: new Date(timestamp),
      description
    };
    if (!existsSync(SESSIONS_DIR)) {
      await mkdir(SESSIONS_DIR, { recursive: true });
    }
    const sessionFile = join$1(SESSIONS_DIR, `${sessionId}.json`);
    await writeFile(sessionFile, JSON.stringify(metadata, null, 2));
    console.log(a.green(`\u2714 Session saved: ${sessionId}`));
    if (description) {
      console.log(a.gray(`  ${description}`));
    }
  } catch (error) {
    console.error(a.red("Failed to save session:"), error);
  }
}
async function listSessions() {
  try {
    const sessionManager = getSessionManager();
    const sessions = await sessionManager.listSessions();
    if (sessions.length === 0) {
      console.log(a.yellow("No sessions found"));
      console.log(a.gray(`
Create a new session with: ${a.green("ccjk session create")}`));
      return;
    }
    console.log(a.green.bold("\n\u{1F4CB} Saved Sessions:\n"));
    const sortedSessions = [...sessions].sort((a, b) => {
      const aTime = a.lastUsedAt?.getTime() || a.createdAt.getTime();
      const bTime = b.lastUsedAt?.getTime() || b.createdAt.getTime();
      return bTime - aTime;
    });
    for (const session of sortedSessions) {
      const nameDisplay = session.name ? a.green(session.name) : a.gray("(unnamed)");
      const idDisplay = a.gray(`[${session.id.substring(0, 8)}]`);
      console.log(`  ${nameDisplay} ${idDisplay}`);
      if (session.provider) {
        console.log(a.gray(`    Provider: ${session.provider}`));
      }
      const createdDate = session.createdAt.toLocaleString();
      console.log(a.gray(`    Created: ${createdDate}`));
      if (session.lastUsedAt) {
        const accessedDate = session.lastUsedAt.toLocaleString();
        console.log(a.gray(`    Last accessed: ${accessedDate}`));
      }
      if (session.history.length > 0) {
        console.log(a.gray(`    History: ${session.history.length} entries`));
      }
      console.log("");
    }
    console.log(a.gray(`Total: ${sessions.length} session(s)`));
    console.log(a.gray(`
Use ${a.green("ccjk --resume <name|id>")} to resume a session`));
  } catch (error) {
    console.error(a.red("Failed to list sessions:"), error);
  }
}
async function restoreSession(sessionId) {
  try {
    if (!existsSync(SESSIONS_DIR)) {
      console.log(a.yellow("No sessions found"));
      return;
    }
    const files = await readdir(SESSIONS_DIR);
    const sessions = files.filter((f) => f.endsWith(".json"));
    if (sessions.length === 0) {
      console.log(a.yellow("No sessions found"));
      return;
    }
    if (!sessionId) {
      const choices = await Promise.all(
        sessions.map(async (file) => {
          const content2 = await readFile(join$1(SESSIONS_DIR, file), "utf-8");
          const metadata2 = JSON.parse(content2);
          const date = new Date(metadata2.timestamp).toLocaleString();
          return {
            name: `${metadata2.id} - ${date}${metadata2.description ? ` - ${metadata2.description}` : ""}`,
            value: metadata2.id
          };
        })
      );
      const { selected } = await inquirer.prompt({
        type: "list",
        name: "selected",
        message: "Select session to restore:",
        choices
      });
      sessionId = selected;
    }
    const sessionFile = join$1(SESSIONS_DIR, `${sessionId}.json`);
    if (!existsSync(sessionFile)) {
      console.log(a.red(`Session not found: ${sessionId}`));
      return;
    }
    const content = await readFile(sessionFile, "utf-8");
    const metadata = JSON.parse(content);
    console.log(a.green(`\u2714 Session restored: ${metadata.id}`));
    if (metadata.description) {
      console.log(a.gray(`  ${metadata.description}`));
    }
  } catch (error) {
    console.error(a.red("Failed to restore session:"), error);
  }
}
async function exportSession(sessionId) {
  try {
    if (!existsSync(SESSIONS_DIR)) {
      console.log(a.yellow("No sessions found"));
      return;
    }
    const files = await readdir(SESSIONS_DIR);
    const sessions = files.filter((f) => f.endsWith(".json"));
    if (sessions.length === 0) {
      console.log(a.yellow("No sessions found"));
      return;
    }
    if (!sessionId) {
      const choices = await Promise.all(
        sessions.map(async (file) => {
          const content2 = await readFile(join$1(SESSIONS_DIR, file), "utf-8");
          const metadata2 = JSON.parse(content2);
          const date = new Date(metadata2.timestamp).toLocaleString();
          return {
            name: `${metadata2.id} - ${date}${metadata2.description ? ` - ${metadata2.description}` : ""}`,
            value: metadata2.id
          };
        })
      );
      const { selected } = await inquirer.prompt({
        type: "list",
        name: "selected",
        message: "Select session to export:",
        choices
      });
      sessionId = selected;
    }
    const sessionFile = join$1(SESSIONS_DIR, `${sessionId}.json`);
    if (!existsSync(sessionFile)) {
      console.log(a.red(`Session not found: ${sessionId}`));
      return;
    }
    const content = await readFile(sessionFile, "utf-8");
    const metadata = JSON.parse(content);
    const markdown = `# Session: ${metadata.id}

**Date:** ${new Date(metadata.timestamp).toLocaleString()}
${metadata.description ? `**Description:** ${metadata.description}
` : ""}
## Details

Session data would be exported here.
`;
    const outputFile = join$1(process__default.cwd(), `${sessionId}.md`);
    await writeFile(outputFile, markdown);
    console.log(a.green(`\u2714 Session exported: ${outputFile}`));
  } catch (error) {
    console.error(a.red("Failed to export session:"), error);
  }
}
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 `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
}
async function getDirSize(dirPath) {
  if (!existsSync(dirPath))
    return 0;
  let totalSize = 0;
  try {
    const entries = await readdir(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      const fullPath = join$1(dirPath, entry.name);
      if (entry.isDirectory()) {
        totalSize += await getDirSize(fullPath);
      } else {
        const fileStat = await stat(fullPath);
        totalSize += fileStat.size;
      }
    }
  } catch {
  }
  return totalSize;
}
async function countFiles(dirPath) {
  if (!existsSync(dirPath))
    return 0;
  let count = 0;
  try {
    const entries = await readdir(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      const fullPath = join$1(dirPath, entry.name);
      if (entry.isDirectory()) {
        count += await countFiles(fullPath);
      } else {
        count++;
      }
    }
  } catch {
  }
  return count;
}
async function analyzeCleanupTargets() {
  const targets = [];
  const ccjkCacheDirs = [
    { name: "ccjk/cache", path: join$1(CCJK_DIR, "cache"), desc: "General cache files", safe: true },
    { name: "ccjk/sessions", path: join$1(CCJK_DIR, "sessions"), desc: "Saved session data", safe: true },
    { name: "ccjk/logs", path: join$1(CCJK_DIR, "logs"), desc: "Log files", safe: true },
    { name: "ccjk/temp", path: join$1(CCJK_DIR, "temp"), desc: "Temporary files", safe: true }
  ];
  const claudeDirs = [
    { name: "claude/projects", path: join$1(CLAUDE_DIR, "projects"), desc: "Claude project caches", safe: true },
    { name: "claude/debug", path: join$1(CLAUDE_DIR, "debug"), desc: "Debug logs and traces", safe: true },
    { name: "claude/file-history", path: join$1(CLAUDE_DIR, "file-history"), desc: "File edit history", safe: true },
    { name: "claude/shell-snapshots", path: join$1(CLAUDE_DIR, "shell-snapshots"), desc: "Shell state snapshots", safe: true },
    { name: "claude/paste-cache", path: join$1(CLAUDE_DIR, "paste-cache"), desc: "Clipboard paste cache", safe: true },
    { name: "claude/todos", path: join$1(CLAUDE_DIR, "todos"), desc: "Todo list files", safe: false },
    { name: "claude/plans", path: join$1(CLAUDE_DIR, "plans"), desc: "Plan files", safe: true },
    { name: "claude/session-env", path: join$1(CLAUDE_DIR, "session-env"), desc: "Session environment data", safe: true },
    { name: "claude/ide", path: join$1(CLAUDE_DIR, "ide"), desc: "IDE integration cache", safe: true }
  ];
  for (const dir of [...ccjkCacheDirs, ...claudeDirs]) {
    if (existsSync(dir.path)) {
      const size = await getDirSize(dir.path);
      const fileCount = await countFiles(dir.path);
      if (size > 0) {
        targets.push({
          name: dir.name,
          path: dir.path,
          description: dir.desc,
          size,
          fileCount,
          safe: dir.safe
        });
      }
    }
  }
  return targets.sort((a, b) => b.size - a.size);
}
async function cleanupSession(options = {}) {
  try {
    console.log(a.green.bold("\n\u{1F9F9} Session & Cache Cleanup\n"));
    console.log(a.gray("Analyzing cleanup targets..."));
    const targets = await analyzeCleanupTargets();
    if (targets.length === 0) {
      console.log(a.green("\u2714 No cleanup needed - everything is clean!"));
      return;
    }
    console.log(a.white.bold("\nCleanup Targets:\n"));
    let totalSize = 0;
    let totalFiles = 0;
    for (const target of targets) {
      totalSize += target.size;
      totalFiles += target.fileCount;
      const sizeStr = formatBytes(target.size).padStart(10);
      const filesStr = `${target.fileCount} files`.padStart(12);
      console.log(`  ${a.yellow(sizeStr)} ${a.gray(filesStr)}  ${a.white(target.name)}`);
      console.log(`  ${a.gray(`                        ${target.description}`)}`);
      console.log(`  ${a.gray(`                        ${target.path}`)}`);
      console.log("");
    }
    console.log(a.white.bold("\u2500".repeat(50)));
    console.log(`  ${a.green(formatBytes(totalSize).padStart(10))} ${a.gray(`${totalFiles} files`.padStart(12))}  ${a.white.bold("Total")}`);
    console.log("");
    if (!options.force) {
      const { confirm } = await inquirer.prompt({
        type: "confirm",
        name: "confirm",
        message: options.all ? `Delete ALL ${targets.length} targets (${formatBytes(totalSize)})?` : "Select targets to clean?",
        default: false
      });
      if (!confirm) {
        console.log(a.yellow("Cleanup cancelled"));
        return;
      }
    }
    let selectedTargets = targets;
    if (!options.all && !options.force) {
      const { selected } = await inquirer.prompt({
        type: "checkbox",
        name: "selected",
        message: "Select targets to clean:",
        choices: targets.map((t) => ({
          name: `${t.name} (${formatBytes(t.size)}, ${t.fileCount} files)`,
          value: t.path,
          checked: t.safe
        }))
      });
      selectedTargets = targets.filter((t) => selected.includes(t.path));
    }
    if (selectedTargets.length === 0) {
      console.log(a.yellow("No targets selected"));
      return;
    }
    console.log(a.gray("\nCleaning up..."));
    let cleanedSize = 0;
    let cleanedFiles = 0;
    for (const target of selectedTargets) {
      try {
        await rm(target.path, { recursive: true, force: true });
        cleanedSize += target.size;
        cleanedFiles += target.fileCount;
        console.log(a.green(`  \u2714 ${target.name}`));
      } catch (error) {
        console.log(a.red(`  \u2716 ${target.name}: ${error}`));
      }
    }
    console.log("");
    console.log(a.green.bold(`\u2714 Cleanup complete!`));
    console.log(a.gray(`  Freed ${formatBytes(cleanedSize)} (${cleanedFiles} files)`));
  } catch (error) {
    console.error(a.red("Failed to cleanup:"), error);
  }
}
async function sessionStatus() {
  try {
    console.log(a.green.bold("\n\u{1F4CA} Session & Cache Status\n"));
    const targets = await analyzeCleanupTargets();
    if (targets.length === 0) {
      console.log(a.green("\u2714 All clean - no cached data found"));
      return;
    }
    let totalSize = 0;
    let totalFiles = 0;
    console.log(a.white.bold("Directory                Size        Files"));
    console.log(a.gray("\u2500".repeat(50)));
    for (const target of targets) {
      totalSize += target.size;
      totalFiles += target.fileCount;
      const name = target.name.padEnd(24);
      const size = formatBytes(target.size).padStart(10);
      const files = String(target.fileCount).padStart(8);
      console.log(`${a.white(name)} ${a.yellow(size)} ${a.gray(files)}`);
    }
    console.log(a.gray("\u2500".repeat(50)));
    console.log(`${a.white.bold("Total".padEnd(24))} ${a.green.bold(formatBytes(totalSize).padStart(10))} ${a.gray(String(totalFiles).padStart(8))}`);
    console.log("");
    console.log(a.gray(`Run ${a.green("ccjk session cleanup")} to free up space`));
    const sessionManager = getSessionManager();
    const stats = await sessionManager.getStatistics();
    if (stats.totalSessions > 0) {
      console.log(a.green.bold("\n\u{1F4DD} Session Statistics\n"));
      console.log(a.white(`Total Sessions: ${a.yellow(String(stats.totalSessions))}`));
      console.log(a.white(`Total History Entries: ${a.yellow(String(stats.totalHistoryEntries))}`));
      if (stats.oldestSession) {
        console.log(a.white(`Oldest Session: ${a.gray(stats.oldestSession.toLocaleString())}`));
      }
      if (stats.newestSession) {
        console.log(a.white(`Newest Session: ${a.gray(stats.newestSession.toLocaleString())}`));
      }
      if (stats.mostRecentlyUsed) {
        console.log(a.white(`Most Recently Used: ${a.gray(stats.mostRecentlyUsed.toLocaleString())}`));
      }
    }
  } catch (error) {
    console.error(a.red("Failed to get status:"), error);
  }
}
async function createSessionCommand(options) {
  try {
    const sessionManager = getSessionManager();
    let name = options.name;
    let provider = options.provider;
    let apiKey = options.apiKey;
    if (!name) {
      const { sessionName } = await inquirer.prompt({
        type: "input",
        name: "sessionName",
        message: "Session name (optional):"
      });
      name = sessionName || void 0;
    }
    if (!provider) {
      const { providerChoice } = await inquirer.prompt({
        type: "list",
        name: "providerChoice",
        message: "Select API provider:",
        choices: [
          { name: "Anthropic (Claude)", value: "anthropic" },
          { name: "OpenAI", value: "openai" },
          { name: "Azure OpenAI", value: "azure" },
          { name: "Custom", value: "custom" },
          { name: "Skip (use default)", value: "" }
        ]
      });
      provider = providerChoice || void 0;
    }
    if (provider && !apiKey) {
      const { key } = await inquirer.prompt({
        type: "password",
        name: "key",
        message: `Enter API key for ${provider} (optional):`,
        mask: "*"
      });
      apiKey = key || void 0;
    }
    const session = await sessionManager.createSession(name, provider, apiKey, {
      codeType: options.codeType
    });
    console.log(a.green(`
\u2714 Session created successfully!`));
    console.log(a.white(`  ID: ${a.green(session.id)}`));
    if (session.name) {
      console.log(a.white(`  Name: ${a.green(session.name)}`));
    }
    if (session.provider) {
      console.log(a.white(`  Provider: ${a.green(session.provider)}`));
    }
    console.log(a.gray(`
Use ${a.green(`ccjk --resume ${session.name || session.id}`)} to resume this session`));
  } catch (error) {
    console.error(a.red("Failed to create session:"), error);
  }
}
async function renameSessionCommand(sessionId, options) {
  try {
    const sessionManager = getSessionManager();
    if (!sessionId) {
      console.log(a.red("Please provide a session ID or name"));
      return;
    }
    let newName = options.name;
    if (!newName) {
      const { name } = await inquirer.prompt({
        type: "input",
        name: "name",
        message: "Enter new session name:",
        validate: (input) => input.trim().length > 0 || "Name cannot be empty"
      });
      newName = name;
    }
    const success = await sessionManager.renameSession(sessionId, newName);
    if (success) {
      console.log(a.green(`\u2714 Session renamed to: ${a.green(newName)}`));
    } else {
      console.log(a.red(`Session not found: ${sessionId}`));
    }
  } catch (error) {
    console.error(a.red("Failed to rename session:"), error);
  }
}
async function deleteSessionCommand(sessionId, options) {
  try {
    const sessionManager = getSessionManager();
    if (!sessionId) {
      console.log(a.red("Please provide a session ID or name"));
      return;
    }
    const session = await sessionManager.loadSession(sessionId);
    if (!session) {
      console.log(a.red(`Session not found: ${sessionId}`));
      return;
    }
    if (!options.force) {
      console.log(a.yellow("\n\u26A0\uFE0F  You are about to delete:"));
      console.log(a.white(`  ID: ${a.green(session.id)}`));
      if (session.name) {
        console.log(a.white(`  Name: ${a.green(session.name)}`));
      }
      console.log(a.white(`  Created: ${a.gray(session.createdAt.toLocaleString())}`));
      console.log(a.white(`  History entries: ${a.gray(String(session.history.length))}`));
      const { confirm } = await inquirer.prompt({
        type: "confirm",
        name: "confirm",
        message: "Are you sure you want to delete this session?",
        default: false
      });
      if (!confirm) {
        console.log(a.yellow("Deletion cancelled"));
        return;
      }
    }
    const success = await sessionManager.deleteSession(sessionId);
    if (success) {
      console.log(a.green(`\u2714 Session deleted: ${sessionId}`));
    } else {
      console.log(a.red(`Failed to delete session: ${sessionId}`));
    }
  } catch (error) {
    console.error(a.red("Failed to delete session:"), error);
  }
}
async function handleSessionCommand(args) {
  const [action, sessionId] = args;
  switch (action) {
    case "save":
      await saveSession();
      break;
    case "list":
    case "ls":
      await listSessions();
      break;
    case "restore":
    case "load":
      await restoreSession(sessionId);
      break;
    case "export":
      await exportSession(sessionId);
      break;
    case "cleanup":
    case "clean":
      await cleanupSession();
      break;
    case "status":
      await sessionStatus();
      break;
    case "create":
    case "new":
      await createSessionCommand({});
      break;
    case "rename":
      if (!sessionId) {
        console.log(a.red("Please provide a session ID to rename"));
        return;
      }
      await renameSessionCommand(sessionId, {});
      break;
    case "delete":
    case "rm":
      if (!sessionId) {
        console.log(a.red("Please provide a session ID to delete"));
        return;
      }
      await deleteSessionCommand(sessionId, {});
      break;
    default:
      console.log();
      console.log(a.cyan.bold("\u{1F4E6} Session Management Commands"));
      console.log();
      console.log(a.white("Usage: ccjk session <action> [id]"));
      console.log();
      console.log(a.white("Actions:"));
      console.log(`${a.gray("  save       ")}Save current session`);
      console.log(`${a.gray("  list       ")}List all sessions`);
      console.log(`${a.gray("  restore    ")}Restore a session`);
      console.log(`${a.gray("  export     ")}Export a session`);
      console.log(`${a.gray("  cleanup    ")}Clean up old sessions`);
      console.log(`${a.gray("  status     ")}Show session status`);
      console.log(`${a.gray("  create     ")}Create a new session`);
      console.log(`${a.gray("  rename     ")}Rename a session`);
      console.log(`${a.gray("  delete     ")}Delete a session`);
      console.log();
      console.log(a.white("Examples:"));
      console.log(a.gray("  ccjk session save"));
      console.log(a.gray("  ccjk session list"));
      console.log(a.gray("  ccjk session restore abc123"));
      break;
  }
}

export { cleanupSession, createSessionCommand, deleteSessionCommand, exportSession, handleSessionCommand, listSessions, renameSessionCommand, restoreSession, saveSession, sessionStatus };
