/**
 * native_agent.js
 * Thin Native Messaging bridge. The host is optional: browser automation works
 * without it, while filesystem/shell/OS tools return a clear install-needed
 * error until the local agent is registered.
 */
(function () {
  'use strict';

  const HOST_NAME = 'com.zhenyu.ai_pm_agent';

  function postNative(payload) {
    return new Promise((resolve) => {
      if (!chrome.runtime?.sendNativeMessage) {
        resolve({ ok: false, error: '当前浏览器不支持 Native Messaging' });
        return;
      }
      chrome.runtime.sendNativeMessage(HOST_NAME, payload, (response) => {
        const err = chrome.runtime.lastError;
        if (err) {
          resolve({
            ok: false,
            error: err.message,
            installRequired: true,
            host: HOST_NAME,
            hint: '需要安装本地 Agent 后才能读写任意磁盘路径、执行白名单命令或控制操作系统。'
          });
          return;
        }
        resolve(response || { ok: true });
      });
    });
  }

  async function call(tool, args = {}) {
    const payload = {
      id: 'native_' + Date.now() + '_' + Math.random().toString(36).slice(2),
      tool,
      args,
      sentAt: new Date().toISOString()
    };
    return await postNative(payload);
  }

  globalThis.AiscNative = {
    hostName: HOST_NAME,
    call
  };
})();
