// src/cli/commands/cache.ts
import { openReadCache } from "../../cache/ReadCache.js";
import { toKeyVal, toKeyValList, fmtNum } from "../renderAI.js";

export interface CacheArgs {
  positional: string[];
  flags: Record<string, string | true>;
}

export async function cmdCache(args: CacheArgs, verbose = false): Promise<number> {
  const sub = args.positional[0] ?? "size";
  const projectDir = typeof args.flags["project-dir"] === "string"
    ? args.flags["project-dir"]
    : process.cwd();

  const cache = openReadCache(projectDir);

  switch (sub) {
    case "size": {
      const s = cache.size();
      if (verbose) {
        console.log(`${s.count} entries`);
        console.log(`${s.bytes} bytes`);
      } else {
        console.log(toKeyVal({ count: s.count, bytes: fmtNum(s.bytes) }));
      }
      return 0;
    }
    case "list": {
      const entries = cache.listEntries();
      if (entries.length === 0) {
        if (verbose) {
          console.log("(empty)");
        }
        return 0;
      }
      if (verbose) {
        for (const e of entries) {
          console.log(`${e.hash}  ${e.path}  ${e.bytes}B  seen:${e.seenCount}`);
        }
      } else {
        const compact = entries.map((e) => ({
          hash: e.hash,
          path: e.path,
          bytes: e.bytes,
          seen: e.seenCount,
        }));
        console.log(toKeyValList(compact));
      }
      return 0;
    }
    case "clear": {
      if (args.flags.confirm !== true) {
        if (verbose) {
          console.error("use --confirm to wipe all cache entries");
        } else {
          console.log("err=confirm-required");
        }
        return 1;
      }
      cache.clearAll();
      if (verbose) {
        console.log("cache cleared");
      } else {
        console.log("ok");
      }
      return 0;
    }
    default: {
      const reason = `unknown-subcommand-${sub}`;
      if (verbose) {
        console.error(`unknown cache subcommand: ${sub}`);
      } else {
        console.log(`err=${reason}`);
      }
      return 1;
    }
  }
}
