/**
 * DashClaw SDK v1 (Legacy): CommonJS compatibility wrapper.
 * For ESM: import { DashClaw } from 'dashclaw/legacy'
 * For CJS: const { DashClaw } = require('dashclaw/legacy')
 */

let _module;

async function loadModule() {
  if (!_module) {
    _module = await import('./dashclaw-v1.js');
  }
  return _module;
}

// Re-export via dynamic import (CJS → ESM bridge)
module.exports = new Proxy({}, {
  get(target, prop) {
    if (prop === '__esModule') return true;
    if (prop === 'then') return undefined; // Prevent Promise-like behavior

    // Return a lazy-loading constructor wrapper
    if (prop === 'GuardBlockedError') {
      const Placeholder = class GuardBlockedError extends Error {
        constructor(decision) {
          const reasons = (decision.reasons || []).join('; ') || 'no reason';
          super(`Guard blocked action: ${decision.decision}. Reasons: ${reasons}`);
          this.name = 'GuardBlockedError';
          this.decision = decision.decision;
          this.reasons = decision.reasons || [];
          this.warnings = decision.warnings || [];
          this.matchedPolicies = decision.matched_policies || [];
          this.riskScore = decision.risk_score ?? null;
        }
      };
      
      // Support instanceof across ESM/CJS boundary
      loadModule().then(m => {
        if (m.GuardBlockedError) {
          Object.defineProperty(Placeholder, Symbol.hasInstance, {
            value: (instance) => instance && (instance.name === 'GuardBlockedError' || instance instanceof m.GuardBlockedError)
          });
        }
      });
      
      return Placeholder;
    }
    if (prop === 'DashClaw' || prop === 'OpenClawAgent' || prop === 'default') {
      return class DashClawProxy {
        constructor(opts) {
          this._opts = opts;
          this._ready = loadModule().then(m => {
            const Cls = m.DashClaw || m.default;
            this._instance = new Cls(opts);
          });

          // Return a proxy that forwards all method calls to the async instance
          return new Proxy(this, {
            get(target, prop) {
              if (prop in target) return target[prop];
              if (prop === 'then') return undefined;

              return async (...args) => {
                await target._ready;
                if (!target._instance[prop]) {
                  throw new Error(`Method ${String(prop)} does not exist on DashClaw`);
                }
                return target._instance[prop](...args);
              };
            }
          });
        }

        // For synchronous construction, use DashClaw.create()
        static async create(opts) {
          const mod = await loadModule();
          const Cls = mod.DashClaw || mod.default;
          return new Cls(opts);
        }
      };
    }
    return undefined;
  }
});

// Preferred: async factory
module.exports.create = async function create(opts) {
  const mod = await loadModule();
  const Cls = mod.DashClaw || mod.default;
  return new Cls(opts);
};
