import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import a from './index5.mjs';
import { MetricsDisplay } from './metrics-display.mjs';
import { getContextPersistence } from './persistence.mjs';
import { r as runHealthCheck } from '../shared/ccjk.Dxgd2vjc.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'better-sqlite3';
import './constants.mjs';
import './index2.mjs';
import 'node:process';
import 'node:url';
import './memory-check.mjs';
import 'node:path';
import 'fs';
import 'constants';
import 'stream';
import 'util';
import 'assert';
import 'path';
import './memory-paths.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './fs-operations.mjs';
import 'node:crypto';
import 'node:fs/promises';

const HABIT_FILE = join(homedir(), ".ccjk", "habits.json");
function loadHabitStats() {
  try {
    if (!existsSync(HABIT_FILE)) {
      return {
        totalCommands: 0,
        lastUsed: 0,
        streak: 0,
        longestStreak: 0,
        commandCounts: {},
        firstUsed: Date.now()
      };
    }
    return JSON.parse(readFileSync(HABIT_FILE, "utf-8"));
  } catch {
    return {
      totalCommands: 0,
      lastUsed: 0,
      streak: 0,
      longestStreak: 0,
      commandCounts: {},
      firstUsed: Date.now()
    };
  }
}
function saveHabitStats(stats) {
  try {
    const dir = join(homedir(), ".ccjk");
    if (!existsSync(dir)) {
      require("node:fs").mkdirSync(dir, { recursive: true });
    }
    writeFileSync(HABIT_FILE, JSON.stringify(stats, null, 2), "utf-8");
  } catch {
  }
}
function updateHabitStats(command) {
  const stats = loadHabitStats();
  const now = Date.now();
  const lastUsedDate = new Date(stats.lastUsed).toDateString();
  const todayDate = new Date(now).toDateString();
  const yesterdayDate = new Date(now - 24 * 60 * 60 * 1e3).toDateString();
  if (lastUsedDate === todayDate) ; else if (lastUsedDate === yesterdayDate) {
    stats.streak++;
  } else {
    stats.streak = 1;
  }
  if (stats.streak > stats.longestStreak) {
    stats.longestStreak = stats.streak;
  }
  stats.commandCounts[command] = (stats.commandCounts[command] || 0) + 1;
  stats.totalCommands++;
  stats.lastUsed = now;
  saveHabitStats(stats);
  return stats;
}
function getDaysUsed() {
  const stats = loadHabitStats();
  if (stats.totalCommands === 0)
    return 0;
  const firstDate = new Date(stats.firstUsed);
  const now = /* @__PURE__ */ new Date();
  const diffTime = Math.abs(now.getTime() - firstDate.getTime());
  const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
  return diffDays;
}
function getMotivationalMessage(stats, tokensSaved, costSavings) {
  const messages = [];
  if (stats.streak >= 7) {
    messages.push(a.green.bold(`\u{1F389} ${stats.streak}-day streak! You're on fire!`));
  } else if (stats.streak >= 3) {
    messages.push(a.cyan(`\u{1F525} ${stats.streak}-day streak! Keep it going!`));
  } else if (stats.streak === 1) {
    messages.push(a.yellow(`\u2728 New streak started! Come back tomorrow!`));
  }
  if (costSavings >= 50) {
    messages.push(a.green.bold(`\u{1F4B0} You've saved $${costSavings.toFixed(2)} this week!`));
  } else if (costSavings >= 10) {
    messages.push(a.cyan(`\u{1F4B5} $${costSavings.toFixed(2)} saved this week!`));
  }
  if (tokensSaved >= 1e5) {
    messages.push(a.magenta.bold(`\u{1F680} ${MetricsDisplay.formatTokenCount(tokensSaved)} tokens saved!`));
  } else if (tokensSaved >= 1e4) {
    messages.push(a.blue(`\u{1F4CA} ${MetricsDisplay.formatTokenCount(tokensSaved)} tokens saved!`));
  }
  if (stats.totalCommands === 10) {
    messages.push(a.yellow(`\u{1F3AF} 10 commands milestone! You're getting the hang of it!`));
  } else if (stats.totalCommands === 50) {
    messages.push(a.green(`\u{1F3C6} 50 commands milestone! You're a power user!`));
  } else if (stats.totalCommands === 100) {
    messages.push(a.magenta.bold(`\u{1F451} 100 commands milestone! You're a CCJK master!`));
  }
  if (stats.longestStreak >= 30) {
    messages.push(a.magenta.bold(`\u{1F3C5} Longest streak: ${stats.longestStreak} days! Legendary!`));
  } else if (stats.longestStreak >= 14) {
    messages.push(a.green(`\u{1F3C5} Longest streak: ${stats.longestStreak} days!`));
  }
  return messages.length > 0 ? messages.join("\n  ") : "";
}
function getSuggestion(stats) {
  const now = Date.now();
  const lastUsed = stats.lastUsed;
  const hoursSinceLastUse = (now - lastUsed) / (1e3 * 60 * 60);
  if (hoursSinceLastUse >= 168) {
    return a.yellow(`\u{1F4A1} Tip: Run ${a.cyan("ccjk cleanup")} weekly to keep DB healthy`);
  }
  if (hoursSinceLastUse >= 24) {
    return a.yellow(`\u{1F4A1} Tip: Run ${a.cyan("ccjk review")} to see your daily stats`);
  }
  if ((stats.commandCounts.commit || 0) < 5) {
    return a.yellow(`\u{1F4A1} Tip: Try ${a.cyan("ccjk commit")} for smart commits with compression stats`);
  }
  const tips = [
    `\u{1F4A1} Tip: ${a.cyan("ccjk morning")} gives you a quick health check`,
    `\u{1F4A1} Tip: ${a.cyan("ccjk review")} shows your token savings`,
    `\u{1F4A1} Tip: ${a.cyan("ccjk cleanup")} keeps your database optimized`
  ];
  return tips[Math.floor(Math.random() * tips.length)];
}
async function morningCommand(options = {}) {
  const stats = updateHabitStats("morning");
  if (!options.silent) {
    console.log();
    console.log(a.cyan.bold("\u2600\uFE0F  Good morning! Here's your CCJK status:"));
    console.log();
  }
  try {
    const health = await runHealthCheck();
    const persistence = getContextPersistence();
    const metrics = persistence.getCompressionMetricsStats();
    if (options.json) {
      console.log(JSON.stringify({
        health,
        metrics,
        habits: stats
      }, null, 2));
      return;
    }
    const gradeColor = health.grade === "S" ? a.magenta.bold : health.grade === "A" ? a.green.bold : health.grade === "B" ? a.cyan.bold : health.grade === "C" ? a.yellow.bold : a.red.bold;
    console.log(`  ${a.gray("Health Score:")} ${gradeColor(health.grade)} ${a.gray(`(${health.totalScore}/100)`)}`);
    if (metrics.totalCompressions > 0) {
      console.log(`  ${a.gray("Total Saved:")} ${a.green(MetricsDisplay.formatTokenCount(metrics.totalTokensSaved))} tokens`);
      console.log(`  ${a.gray("Cost Savings:")} ${a.green.bold(MetricsDisplay.formatCost(metrics.estimatedCostSavings))}`);
      if (metrics.sessionStats && metrics.sessionStats.compressions > 0) {
        console.log(`  ${a.gray("Last 24h:")} ${a.white(metrics.sessionStats.compressions)} compressions, ${a.green(MetricsDisplay.formatCost(metrics.sessionStats.costSavings))} saved`);
      }
    }
    if (stats.streak > 0) {
      console.log(`  ${a.gray("Streak:")} ${a.yellow(`${stats.streak} day${stats.streak > 1 ? "s" : ""}`)}`);
    }
    console.log();
    const message = getMotivationalMessage(stats, metrics.totalTokensSaved, metrics.weeklyStats?.costSavings || 0);
    if (message) {
      console.log(`  ${message}`);
      console.log();
    }
    if (health.recommendations.length > 0) {
      console.log(a.yellow.bold("  \u{1F4CB} Top Recommendations:"));
      for (const rec of health.recommendations.slice(0, 2)) {
        const priority = rec.priority === "high" ? a.red("!") : rec.priority === "medium" ? a.yellow("\u2022") : a.gray("\xB7");
        console.log(`  ${priority} ${rec.title}`);
        if (rec.command) {
          console.log(`    ${a.gray("\u2192")} ${a.cyan(rec.command)}`);
        }
      }
      console.log();
    }
    const suggestion = getSuggestion(stats);
    if (suggestion) {
      console.log(`  ${suggestion}`);
      console.log();
    }
  } catch (error) {
    console.error(a.red("Error running morning command:"), error);
    process.exit(1);
  }
}
async function reviewCommand(options = {}) {
  const stats = updateHabitStats("review");
  if (!options.silent) {
    console.log();
    console.log(a.cyan.bold("\u{1F4CA} Daily Review"));
    console.log();
  }
  try {
    const persistence = getContextPersistence();
    const metrics = persistence.getCompressionMetricsStats();
    if (options.json) {
      console.log(JSON.stringify({
        metrics,
        habits: stats
      }, null, 2));
      return;
    }
    console.log(a.cyan.bold("  Overall Statistics"));
    console.log(`  ${a.gray("Total Compressions:")} ${a.white(metrics.totalCompressions)}`);
    console.log(`  ${a.gray("Total Saved:")} ${a.green(MetricsDisplay.formatTokenCount(metrics.totalTokensSaved))} tokens`);
    console.log(`  ${a.gray("Avg Reduction:")} ${a.yellow(MetricsDisplay.formatRatio(metrics.averageCompressionRatio))}`);
    console.log(`  ${a.gray("Cost Savings:")} ${a.green.bold(MetricsDisplay.formatCost(metrics.estimatedCostSavings))}`);
    console.log();
    if (metrics.sessionStats && metrics.sessionStats.compressions > 0) {
      console.log(a.cyan.bold("  Last 24 Hours"));
      console.log(`  ${a.gray("Compressions:")} ${a.white(metrics.sessionStats.compressions)}`);
      console.log(`  ${a.gray("Tokens Saved:")} ${a.green(MetricsDisplay.formatTokenCount(metrics.sessionStats.tokensSaved))}`);
      console.log(`  ${a.gray("Cost Savings:")} ${a.green(MetricsDisplay.formatCost(metrics.sessionStats.costSavings))}`);
      console.log();
    }
    if (metrics.weeklyStats && metrics.weeklyStats.compressions > 0) {
      console.log(a.cyan.bold("  Last 7 Days"));
      console.log(`  ${a.gray("Compressions:")} ${a.white(metrics.weeklyStats.compressions)}`);
      console.log(`  ${a.gray("Tokens Saved:")} ${a.green(MetricsDisplay.formatTokenCount(metrics.weeklyStats.tokensSaved))}`);
      console.log(`  ${a.gray("Cost Savings:")} ${a.green(MetricsDisplay.formatCost(metrics.weeklyStats.costSavings))}`);
      console.log();
    }
    if (metrics.monthlyStats && metrics.monthlyStats.compressions > 0) {
      console.log(a.cyan.bold("  Last 30 Days"));
      console.log(`  ${a.gray("Compressions:")} ${a.white(metrics.monthlyStats.compressions)}`);
      console.log(`  ${a.gray("Tokens Saved:")} ${a.green(MetricsDisplay.formatTokenCount(metrics.monthlyStats.tokensSaved))}`);
      console.log(`  ${a.gray("Cost Savings:")} ${a.green(MetricsDisplay.formatCost(metrics.monthlyStats.costSavings))}`);
      console.log();
    }
    console.log(a.cyan.bold("  Your Habits"));
    console.log(`  ${a.gray("Total Commands:")} ${a.white(stats.totalCommands)}`);
    console.log(`  ${a.gray("Current Streak:")} ${a.yellow(`${stats.streak} day${stats.streak !== 1 ? "s" : ""}`)}`);
    console.log(`  ${a.gray("Longest Streak:")} ${a.yellow(`${stats.longestStreak} day${stats.longestStreak !== 1 ? "s" : ""}`)}`);
    console.log(`  ${a.gray("Days Active:")} ${a.white(getDaysUsed())}`);
    console.log();
    const message = getMotivationalMessage(stats, metrics.totalTokensSaved, metrics.weeklyStats?.costSavings || 0);
    if (message) {
      console.log(`  ${message}`);
      console.log();
    }
    const suggestion = getSuggestion(stats);
    if (suggestion) {
      console.log(`  ${suggestion}`);
      console.log();
    }
  } catch (error) {
    console.error(a.red("Error running review command:"), error);
    process.exit(1);
  }
}
async function cleanupCommand(options = {}) {
  const stats = updateHabitStats("cleanup");
  if (!options.silent) {
    console.log();
    console.log(a.cyan.bold("\u{1F9F9} Database Cleanup"));
    console.log();
  }
  try {
    const persistence = getContextPersistence();
    const statsBefore = persistence.getStats();
    if (!options.silent) {
      console.log(`  ${a.gray("Database size before:")} ${a.white(MetricsDisplay.formatBytes(statsBefore.totalSize))}`);
      console.log(`  ${a.gray("Total contexts:")} ${a.white(statsBefore.totalContexts)}`);
      console.log();
    }
    const maxAge = 30 * 24 * 60 * 60 * 1e3;
    const deletedContexts = persistence.cleanup(maxAge);
    if (!options.silent && deletedContexts > 0) {
      console.log(`  ${a.green("\u2713")} Deleted ${a.white(deletedContexts)} old context${deletedContexts !== 1 ? "s" : ""}`);
    }
    const metricsMaxAge = 90 * 24 * 60 * 60 * 1e3;
    const deletedMetrics = persistence.cleanupCompressionMetrics(metricsMaxAge);
    if (!options.silent && deletedMetrics > 0) {
      console.log(`  ${a.green("\u2713")} Deleted ${a.white(deletedMetrics)} old metric${deletedMetrics !== 1 ? "s" : ""}`);
    }
    if (!options.silent) {
      console.log(`  ${a.gray("Running VACUUM...")}`);
    }
    persistence.vacuum();
    const statsAfter = persistence.getStats();
    const sizeSaved = statsBefore.totalSize - statsAfter.totalSize;
    if (!options.silent) {
      console.log(`  ${a.green("\u2713")} VACUUM complete`);
      console.log();
      console.log(`  ${a.gray("Database size after:")} ${a.white(MetricsDisplay.formatBytes(statsAfter.totalSize))}`);
      console.log(`  ${a.gray("Space reclaimed:")} ${a.green(MetricsDisplay.formatBytes(sizeSaved))}`);
      console.log(`  ${a.gray("Total contexts:")} ${a.white(statsAfter.totalContexts)}`);
      console.log();
      console.log(`  ${a.green.bold("\u2713 Cleanup complete!")}`);
      console.log();
    }
    if (options.json) {
      console.log(JSON.stringify({
        deletedContexts,
        deletedMetrics,
        sizeSaved,
        statsBefore,
        statsAfter
      }, null, 2));
    }
    if (!options.silent) {
      const message = getMotivationalMessage(stats, 0, 0);
      if (message) {
        console.log(`  ${message}`);
        console.log();
      }
      console.log(`  ${a.yellow(`\u{1F4A1} Tip: Run cleanup weekly to keep your database healthy`)}`);
      console.log();
    }
  } catch (error) {
    console.error(a.red("Error running cleanup command:"), error);
    process.exit(1);
  }
}

export { cleanupCommand, morningCommand, reviewCommand };
