/**
 * 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 {
      fs.writeFileSync(this._getGoalsPath(), JSON.stringify(goals, 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 }
