var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/core/index.ts
var core_exports = {};
__export(core_exports, {
  PisellOSCore: () => PisellOSCore,
  default: () => core_default
});
module.exports = __toCommonJS(core_exports);
var import_createStore = require("../store/createStore");
var import_effects = require("../effects");
var PisellOSCore = class {
  // 保存 Server 配置
  constructor(options) {
    this.plugins = /* @__PURE__ */ new Map();
    this.modules = /* @__PURE__ */ new Map();
    this.stores = /* @__PURE__ */ new Map();
    this.effects = new import_effects.EffectsManager();
    this.debug = false;
    this.context = {};
    this.debug = (options == null ? void 0 : options.debug) || false;
    this.context = (options == null ? void 0 : options.context) || {};
    if (options == null ? void 0 : options.server) {
      this.serverOptions = options.server;
    }
    this.initialize(options);
    console.log("constructor1234");
  }
  initialize(options) {
    if (options == null ? void 0 : options.plugins) {
      options.plugins.forEach((item) => {
        this.registerPlugin(item.plugin, item.options);
      });
    }
    if (options == null ? void 0 : options.modules) {
      options.modules.forEach((item) => {
        this.registerModule(item.module, item.options);
      });
    }
    this.log("[PisellOS] 核心初始化完成");
  }
  /**
   * 初始化 Server（公开方法，需要外部显式调用并等待）
   * Server 配置从构造函数传入的 options.server 中获取
   */
  async initializeServer(options) {
    if (this.server) {
      this.log("Server 已经初始化，跳过重复初始化", "warn");
      return;
    }
    if (!this.serverOptions) {
      this.log("未提供 Server 配置，无法初始化", "warn");
      return;
    }
    try {
      const ServerModule = await import("../server");
      const Server = ServerModule.default;
      this.server = new Server(this);
      this.log("Server 实例已创建");
      if (this.serverOptions.modules) {
        await this.server.initialize(
          this.serverOptions.modules,
          this.serverOptions.autoInitData !== false,
          options
        );
      }
      console.log("[PisellOS] ✅ Server 初始化完成，所有数据已预加载");
      this.log("[PisellOS] Server 初始化完成");
    } catch (error) {
      console.error("[PisellOS] ❌ Server 初始化失败:", error);
      this.log(`Server 初始化失败: ${error}`, "error");
      throw error;
    }
  }
  // 日志方法
  log(message, level = "info") {
    if (!this.debug && level === "info") {
      return;
    }
    const prefix = "[PisellOS]";
    switch (level) {
      case "info":
        console.log(`${prefix} ${message}`);
        break;
      case "warn":
        console.log(`%c${prefix}%c ${message}`, "color: #f59e0b; font-weight: bold;", "color: #f59e0b;");
        break;
      case "error":
        console.error(`${prefix} ${message}`);
        break;
    }
  }
  // 插件相关方法
  registerPlugin(plugin, options) {
    if (this.plugins.has(plugin.name)) {
      this.log(`插件 ${plugin.name} 已经注册过，将被覆盖`, "warn");
    }
    if (options == null ? void 0 : options.dependencies) {
      for (const dep of options.dependencies) {
        if (!this.plugins.has(dep)) {
          throw new Error(`注册插件 ${plugin.name} 失败：缺少依赖插件 ${dep}`);
        }
      }
    }
    try {
      const result = plugin.initialize();
      if (result instanceof Promise) {
        result.catch((err) => {
          this.log(`插件 ${plugin.name} 初始化失败: ${err.message}`, "error");
          throw err;
        });
      }
      this.plugins.set(plugin.name, plugin);
      this.log(`插件 ${plugin.name} v${plugin.version} 注册成功`);
    } catch (error) {
      this.log(`插件 ${plugin.name} 初始化过程中出错: ${error}`, "error");
      throw error;
    }
  }
  getPlugin(name) {
    return this.plugins.get(name) || null;
  }
  hasPlugin(name) {
    return this.plugins.has(name);
  }
  // 模块相关方法
  registerModule(module2, options) {
    if (this.modules.has(module2.name)) {
      this.log(`模块 ${module2.name} 已经注册过，将被覆盖`, "warn");
    }
    if (options == null ? void 0 : options.dependencies) {
      for (const dep of options.dependencies) {
        if (!this.modules.has(dep)) {
          throw new Error(`注册模块 ${module2.name} 失败：缺少依赖模块 ${dep}`);
        }
      }
    }
    if (options == null ? void 0 : options.plugins) {
      for (const plugin of options.plugins) {
        if (!this.plugins.has(plugin)) {
          throw new Error(
            `注册模块 ${module2.name} 失败：缺少依赖插件 ${plugin}`
          );
        }
      }
    }
    const { proxy } = (0, import_createStore.createStore)(
      (options == null ? void 0 : options.initialState) || {},
      module2.name,
      (path, value) => {
        console.log("core 检测到模块值更新", module2.name, path, value);
        this.effects.emit(`${module2.name}:changed`, { path, value });
        if (module2.storeChange)
          module2.storeChange(path, value);
      }
    );
    this.stores.set(module2.name, proxy);
    try {
      const result = module2.initialize(this, { store: proxy, ...options });
      if (result instanceof Promise) {
        result.catch((err) => {
          this.log(`模块 ${module2.name} 初始化失败: ${err.message}`, "error");
          throw err;
        });
      }
      this.modules.set(module2.name, module2);
      this.log(`模块 ${module2.name} v${module2.version} 注册成功`);
    } catch (error) {
      this.log(`模块 ${module2.name} 初始化过程中出错: ${error}`, "error");
      throw error;
    }
  }
  unregisterModule(module2) {
    this.stores.delete(module2.name);
    this.modules.delete(module2.name);
  }
  getModule(name) {
    return this.modules.get(name) || null;
  }
  getModuleExports(name) {
    const module2 = this.modules.get(name);
    return (module2 == null ? void 0 : module2.exports) || null;
  }
  hasModule(name) {
    return this.modules.has(name);
  }
  // 销毁方法
  async destroy() {
    for (const [name, module2] of this.modules.entries()) {
      if (module2.destroy) {
        try {
          await Promise.resolve(module2.destroy());
          this.log(`模块 ${name} 已销毁`);
        } catch (error) {
          this.log(`销毁模块 ${name} 时出错: ${error}`, "error");
        }
      }
    }
    this.modules.clear();
    for (const [name, plugin] of this.plugins.entries()) {
      if (plugin.destroy) {
        try {
          await Promise.resolve(plugin.destroy());
          this.log(`插件 ${name} 已销毁`);
        } catch (error) {
          this.log(`销毁插件 ${name} 时出错: ${error}`, "error");
        }
      }
    }
    this.plugins.clear();
    this.log("PisellOS 核心已销毁");
  }
  setContext(ctx) {
    this.context = { ...this.context, ...ctx };
    this.log(`上下文已更新: ${JSON.stringify(Object.keys(ctx))}`);
  }
  /**
   * 验证上下文参数
   */
  validateContext(config) {
    for (const rule of config.validations) {
      const value = this.context[rule.name];
      if (rule.required && (value === void 0 || value === null)) {
        this.log(
          `模块 ${config.name} 缺少必需的上下文参数: ${rule.name}`,
          "error"
        );
        return false;
      }
      if (rule.validate && value !== void 0 && value !== null) {
        if (!rule.validate(value)) {
          this.log(
            `模块 ${config.name} 上下文参数验证失败: ${rule.name} - ${rule.message || "验证失败"}`,
            "error"
          );
          return false;
        }
      }
    }
    return true;
  }
};
var core_default = PisellOSCore;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PisellOSCore
});
