src / tools / stateManager.ts

import { readFile, writeFile, mkdir } from "fs/promises";
import { join } from "path";
import * as os from "os";

const CONFIG_FILE_NAME = ".plugin_state.json";
const DEFAULT_DIR = join(os.homedir(), ".maestro-toolbox", "workspace");
const STATE_PATH = join(os.homedir(), ".maestro-toolbox", CONFIG_FILE_NAME);

export interface PluginState {
  currentWorkingDirectory: string;
  messageCount: number;
  /** Files saved with content > 10KB in this session — used to suggest replace_text_in_file */
  largeFilesSaved?: string[];
}

const DEFAULT_STATE: PluginState = {
  currentWorkingDirectory: DEFAULT_DIR,
  messageCount: 0,
};

/** In-memory cache — avoids reading from disk on every call. */
let _cached: PluginState | null = null;

export async function getPersistedState(): Promise<PluginState> {
  if (_cached) return _cached;
  try {
    const content = await readFile(STATE_PATH, "utf-8");
    const state = JSON.parse(content);
    _cached = {
      currentWorkingDirectory: state.currentWorkingDirectory ?? DEFAULT_DIR,
      messageCount: state.messageCount ?? 0,
      largeFilesSaved: state.largeFilesSaved ?? [],
    };
    return _cached;
  } catch {
    _cached = { ...DEFAULT_STATE };
    return _cached;
  }
}

export async function savePersistedState(state: PluginState) {
  _cached = state; // update cache immediately
  try {
    const dir = join(os.homedir(), ".maestro-toolbox");
    await mkdir(dir, { recursive: true });
    await writeFile(STATE_PATH, JSON.stringify(state, null, 2), "utf-8");
  } catch (error) {
    console.error("Failed to save plugin state:", error);
  }
}

export async function ensureWorkspaceExists(path: string) {
  try {
    await mkdir(path, { recursive: true });
  } catch (error) {
    console.error(`Failed to create/access directory ${path}`, error);
  }
}