/**
 * @author: xujianjiang
 * 自定义扩展示例
 *
 * 放置位置：config/agent/extensions/
 * 安装后会复制到 ~/.pi/agent/extensions/
 *
 * 可以拦截内置工具、注册自定义工具和命令
 */

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";

export default function (pi: ExtensionAPI) {
  // === 拦截工具调用 ===

  pi.on("tool_call", async (event, ctx) => {
    try {
      // 拦截 login 工具 - 阻止执行
      if (event.toolName === "login") {
        await ctx.ui.notify("⚠️ login 功能已禁用", "warning");
        return { block: true, reason: "login 功能已禁用" };
      }

      // 拦截 logout 工具 - 阻止执行
      if (event.toolName === "logout") {
        await ctx.ui.notify("⚠️ logout 功能已禁用", "warning");
        return { block: true, reason: "logout 功能已禁用" };
      }
    } catch (e) {
      // 忽略错误（ctx 可能已过期）
    }
    return;
  });

  // === 注册自定义命令 ===

  pi.registerCommand("hello", {
    description: "打招呼命令",
    handler: async (args, ctx) => {
      try {
        const name = args || "大佬，您吃了吗";
        ctx.ui.notify(`你好，${name}！🤝`, "info");
      } catch (e) {
        // 忽略错误
      }
    },
  });

  pi.registerCommand("status", {
    description: "显示当前会话状态",
    handler: async (_args, ctx) => {
      try {
        // 保存需要的数据，避免多次触发 getter
        const model = ctx.model?.name || "未知";
        const entries = ctx.sessionManager.getEntries();
        const messages = entries.filter((e) => e.type === "message").length;

        const info = `
📊 会话状态

- 当前模型：${model}
- 消息数量：${messages}
      `.trim();
        ctx.ui.notify(info, "info");
      } catch (e) {
        // 忽略错误（ctx 可能已过期）
      }
    },
  });

  pi.registerCommand("clear", {
    description: "清理当前会话上下文",
    handler: async (_args, ctx) => {
      try {
        // 获取当前会话条目数（在 await 前完成所有 ctx 访问）
        const entries = ctx.sessionManager.getBranch();
        const msgCount = entries.filter((e) => e.type === "message").length;
        const uiContext = ctx.ui; // ← 保存 UI context

        if (msgCount === 0) {
          uiContext.notify("会话已经是空的", "info");
          return;
        }

        // 确认清理
        const ok = await uiContext.confirm(
          "清理会话",
          `确定要清理当前会话的所有 ${msgCount} 条消息吗？`,
        );
        if (!ok) {
          uiContext.notify("已取消", "info");
          return;
        }

        // 创建新会话来清空上下文
        await ctx.newSession({
          withSession: async (newCtx) => {
            newCtx.ui.notify(
              `✅ 已清理 ${msgCount} 条消息，进入新会话`,
              "info",
            );
          },
        });
      } catch (e) {
        // 忽略错误（ctx 可能已过期）
      }
    },
  });

  // === 注册 /exit 命令 ===

  pi.registerCommand("exit", {
    description: "退出当前会话",
    handler: async (_args, ctx) => {
      try {
        ctx.ui.notify("👋 再见！", "info");
        ctx.shutdown();
      } catch (e) {
        // 忽略错误
      }
    },
  });

  // === 注册 /update 命令 ===

  pi.registerCommand("update", {
    description: "更新 aicode-cli 工具",
    handler: async (_args, ctx) => {
      try {
        // ← 在 await 前保存 UI context
        const uiContext = ctx.ui;

        const ok = await uiContext.confirm(
          "更新确认",
          "确定要更新 aicode-cli 吗？",
        );
        if (!ok) {
          uiContext.notify("已取消", "info");
          return;
        }

        uiContext.notify("🔄 正在更新 aicode-cli...", "info");

        // 使用 Promise 包装 exec
        const { exec } = await import("child_process");
        await new Promise<void>((resolve) => {
          exec("npm install -g @ia-ccun/code-agent-cli", (error) => {
            if (error) {
              uiContext.notify(
                `❌ 更新失败：${error.message}，请重试`,
                "error",
              );
            } else {
              uiContext.notify("✅ aicode-cli 更新成功！请重启 CLI", "info");
            }
            resolve();
          });
        });
      } catch (e) {
        // 忽略错误（ctx 可能已过期）
      }
    },
  });

  // === 注册自定义工具 ===

  // 注意：注册自定义工具需要更复杂的参数定义
  // 详情请参考：https://github.com/mariozechner/pi-coding-agent/docs/extensions.md

  // === 注册 /version 命令 ===

  pi.registerCommand("version", {
    description: "查看当前版本和最新版本",
    handler: async (_args, ctx) => {
      const { execSync } = await import("child_process");
      const { readFileSync, existsSync } = await import("fs");

      // 读取全局安装的 aicode-cli 版本
      let localVersion = "未知";
      try {
        // 获取全局 npm 包路径
        const globalPath = execSync("npm root -g", { encoding: "utf8" }).trim();
        const pkgPath = `${globalPath}/@ia-ccun/code-agent-cli/package.json`;

        if (existsSync(pkgPath)) {
          const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
          localVersion = pkg.version;
        }
      } catch (e) {
        // 忽略
      }

      // 获取最新版本
      let latestVersion = "未知";
      let updateMsg = "";
      try {
        const registry = execSync("npm config get registry", {
          encoding: "utf8",
        }).trim();
        latestVersion = execSync(
          `npm view @ia-ccun/code-agent-cli version --registry=${registry}`,
          { encoding: "utf8" },
        ).trim();

        // 比较版本
        const localParts = localVersion.split(".").map(Number);
        const latestParts = latestVersion.split(".").map(Number);
        const needsUpdate =
          latestParts[0] > localParts[0] ||
          (latestParts[0] === localParts[0] &&
            latestParts[1] > localParts[1]) ||
          (latestParts[0] === localParts[0] &&
            latestParts[1] === localParts[1] &&
            latestParts[2] > localParts[2]);

        if (needsUpdate) {
          updateMsg = `\n\n⚠️  发现新版本 v${localVersion} → v${latestVersion}\n   运行：npm install -g @ia-ccun/code-agent-cli`;
        } else {
          updateMsg = "\n\n✅ 已是最新版本";
        }
      } catch (e) {
        updateMsg = "\n\n❌ 最新版本检查异常，请稍后重试";
      }

      const info = `
📦 版本信息

   当前版本：v${localVersion}
   最新版本：v${latestVersion}
${updateMsg}
      `.trim();

      ctx.ui.notify(info, "info");
    },
  });
}
