/**
 * StateStore - 持久化目标和记忆到文件系统
 */

const fs = require('fs')
const path = require('path')
const { logger } = require('../../src/utils/logger')

const log = logger.child('Ambient:StateStore')

class StateStore {
  constructor(persistencePath) {
    this._persistencePath = persistencePath
    this._ensureDir()
  }

  _ensureDir() {
    if (!fs.existsSync(this._persistencePath)) {
      fs.mkdirSync(this._persistencePath, { recursive: true })
    }
  }

  _getGoalsPath() {
    return path.join(this._persistencePath, 'goals.json')
  }

  _getMemoriesPath() {
    return path.join(this._persistencePath, 'memories.json')
  }

  /**
   * 保存目标列表到文件
   * @param {Array} goals - 目标数组
   */
  saveGoals(goals) {
    try {
      // 过滤掉循环引用的运行时数据，只保留可序列化的字段
      const filtered = goals.map(g => ({
        id: g.id,
        title: g.title,
        description: g.description,
        priority: g.priority,
        state: g.state,
        actions: g.actions?.map(a => ({
          id: a.id,
          type: a.type,
          name: a.name,
          args: a.args,
          content: a.content,
          topic: a.topic,
          mode: a.mode,
          completed: a.completed,
          order: a.order
        })),
        conditions: g.conditions,
        persistent: g.persistent,
        createdAt: g.createdAt,
        updatedAt: g.updatedAt,
        activatedAt: g.activatedAt,
        completedAt: g.completedAt,
        failedAt: g.failedAt,
        attempts: g.attempts,
        maxAttempts: g.maxAttempts,
        eventsReceived: []  // 不保存运行时事件
      }))
      fs.writeFileSync(this._getGoalsPath(), JSON.stringify(filtered, null, 2))
    } catch (err) {
      log.error('保存目标失败:', err.message)
    }
  }

  /**
   * 从文件加载目标列表
   * @returns {Array} 目标数组
   */
  loadGoals() {
    try {
      const filePath = this._getGoalsPath()
      if (fs.existsSync(filePath)) {
        const data = fs.readFileSync(filePath, 'utf-8')
        return JSON.parse(data)
      }
    } catch (err) {
      log.error('加载目标失败:', err.message)
    }
    return []
  }

  /**
   * 保存记忆列表到文件
   * @param {Array} memories - 记忆数组
   */
  saveMemories(memories) {
    try {
      fs.writeFileSync(this._getMemoriesPath(), JSON.stringify(memories, null, 2))
    } catch (err) {
      log.error('保存记忆失败:', err.message)
    }
  }

  /**
   * 从文件加载记忆列表
   * @returns {Array} 记忆数组
   */
  loadMemories() {
    try {
      const filePath = this._getMemoriesPath()
      if (fs.existsSync(filePath)) {
        const data = fs.readFileSync(filePath, 'utf-8')
        return JSON.parse(data)
      }
    } catch (err) {
      log.error('加载记忆失败:', err.message)
    }
    return []
  }
}

module.exports = { StateStore }
