src / memoryManager.ts

import fs from 'fs';
import path from 'path';

export interface MemorySlot {
  id: number;
  key: string;
  data: unknown;
  createdAt: string;
  updatedAt: string;
}

export class MemoryManager {
  private slots: MemorySlot[] = [];
  private filePath: string;

  constructor() {
    this.filePath = path.join(__dirname, '../memory.json');
    this.load();
  }

  private load() {
    if (fs.existsSync(this.filePath)) {
      try {
        const data = fs.readFileSync(this.filePath, 'utf-8');
        this.slots = JSON.parse(data);
        this.slots.forEach(s => {
          s.id = Number(s.id);
          if (!s.createdAt) s.createdAt = new Date().toISOString();
          if (!s.updatedAt) s.updatedAt = s.createdAt;
        });
      } catch (e) {
        console.error("Failed to parse memory.json", e);
        this.slots = [];
      }
    } else {
      this.slots = [];
    }
  }

  private save() {
    try {
      fs.writeFileSync(this.filePath, JSON.stringify(this.slots, null, 2));
    } catch (e) {
      console.error("Failed to save memory.json", e);
    }
  }

  add(key: string, data: unknown): string {
    const maxId = this.slots.length > 0 ? Math.max(...this.slots.map(s => s.id)) : 0;
    const id = maxId + 1;
    const now = new Date().toISOString();

    this.slots.push({
      id,
      key,
      data,
      createdAt: now,
      updatedAt: now,
    });
    this.save();
    return `Success: Added memory slot #${id} with key "${key}"`;
  }

  read(key?: string, id?: number): string {
    if (key !== undefined) {
      const slot = this.slots.find(s => s.key === key);
      if (!slot) {
        return `Error: Memory slot with key "${key}" not found.`;
      }
      return `Memory slot #${slot.id} [${slot.key}]:\n${JSON.stringify(slot.data, null, 2)}`;
    }

    if (id !== undefined) {
      const slot = this.slots.find(s => s.id === id);
      if (!slot) {
        return `Error: Memory slot #${id} not found.`;
      }
      return `Memory slot #${slot.id} [${slot.key}]:\n${JSON.stringify(slot.data, null, 2)}`;
    }

    if (this.slots.length === 0) {
      return "Status: Memory is empty.";
    }

    let output = `--- MEMORY SLOTS (${this.slots.length} total) ---\n`;
    output += this.slots.map(s => `[#${s.id}] ${s.key} (updated: ${s.updatedAt})`).join('\n');
    return output;
  }

  update(id: number, key?: string, data?: unknown): string {
    const slot = this.slots.find(s => s.id === Number(id));

    if (!slot) {
      return `Error: Memory slot #${id} not found.`;
    }

    if (key !== undefined) slot.key = key;
    if (data !== undefined) slot.data = data;
    slot.updatedAt = new Date().toISOString();

    this.save();
    return `Success: Updated memory slot #${id} [${slot.key}]`;
  }

  remove(id: number): string {
    const startCount = this.slots.length;
    this.slots = this.slots.filter(s => s.id !== Number(id));

    if (this.slots.length === startCount) {
      return `Error: Memory slot #${id} not found.`;
    }

    this.save();
    return `Success: Memory slot #${id} deleted.`;
  }

  clear(): string {
    const count = this.slots.length;
    this.slots = [];
    this.save();
    return `Success: Cleared all ${count} memory slots.`;
  }
}