const fs = require('fs');
const path = require('path');

global.chrome = {
  storage: {
    local: {
      get: async (keys) => {
        const store = {};
        if (typeof keys === 'string') keys = [keys];
        for (const key of keys) {
          store[key] = global.__chromeStore?.[key] ?? undefined;
        }
        return store;
      },
      set: async (items) => {
        global.__chromeStore = { ...global.__chromeStore, ...items };
      }
    }
  }
};

global.__chromeStore = {};

const moduleCache = {};

async function loadModule(filePath) {
  const absPath = path.resolve(filePath);
  console.log('loadModule called with:', absPath);
  if (moduleCache[absPath]) {
    console.log('  -> cache hit');
    return moduleCache[absPath];
  }
  
  const content = fs.readFileSync(absPath, 'utf-8');
  const dir = path.dirname(absPath);
  
  const exportedNames = [];
  let modified = content;
  
  modified = modified.replace(
    /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"];?/g,
    (match, imports, source) => {
      const cleanSource = source.replace(/\.js$/, '');
      return `const { ${imports} } = require('${cleanSource}');`;
    }
  );
  
  modified = modified.replace(
    /import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"];?/g,
    (match, name, source) => {
      const cleanSource = source.replace(/\.js$/, '');
      return `const ${name} = require('${cleanSource}');`;
    }
  );
  
  modified = modified.replace(
    /import\s+(\w+)\s+from\s*['"]([^'"]+)['"];?/g,
    (match, name, source) => {
      const cleanSource = source.replace(/\.js$/, '');
      return `const ${name} = require('${cleanSource}');`;
    }
  );
  
  modified = modified.replace(/export\s+async\s+function\s+(\w+)/g, (match, name) => {
    exportedNames.push(name);
    return `async function ${name}`;
  });
  modified = modified.replace(/export\s+function\s+(\w+)/g, (match, name) => {
    exportedNames.push(name);
    return `function ${name}`;
  });
  modified = modified.replace(/export\s+const\s+(\w+)/g, (match, name) => {
    exportedNames.push(name);
    return `const ${name}`;
  });
  
  modified = modified.replace(
    /export\s*\{([^}]+)\};?/g,
    (match, names) => {
      const assignments = names.split(',').map(n => n.trim()).filter(Boolean).map(n => {
        const [orig, alias] = n.split(' as ').map(s => s.trim());
        exportedNames.push(alias || orig);
        return `${alias || orig}: ${orig}`;
      });
      return `module.exports = { ${assignments.join(', ')} };`;
    }
  );
  
  if (!modified.includes('module.exports') && exportedNames.length > 0) {
    const uniqueExports = [...new Set(exportedNames)];
    const exportsStr = uniqueExports.map(n => `${n}: ${n}`).join(', ');
    modified += `\nmodule.exports = { ${exportsStr} };\n`;
  }
  
  console.log('  -> modified code snippet:', modified.slice(0, 200));
  
  const customRequire = (id) => {
    console.log('  -> customRequire called with:', id);
    if (id.startsWith('.')) {
      const base = id.endsWith('.js') ? id : id + '.js';
      const resolved = path.resolve(dir, base);
      console.log('  -> resolved to:', resolved);
      return loadModule(resolved);
    }
    return require(id);
  };
  
  const moduleObj = { exports: {} };
  const fn = new Function('module', 'exports', 'require', 'console', 'crypto', 'global', modified);
  fn(moduleObj, moduleObj.exports, customRequire, console, globalThis.crypto, global);
  
  console.log('  -> moduleObj.exports:', Object.keys(moduleObj.exports));
  moduleCache[absPath] = moduleObj.exports;
  return moduleObj.exports;
}

async function main() {
  const buildDir = '/home/node/.openclaw/workspace/agents/bunbun/builds/agent-police-department-claude-code-agent-governan';
  
  const hashMod = await loadModule(path.join(buildDir, 'lib/hash.js'));
  console.log('hashMod:', Object.keys(hashMod));
  
  const auditMod = await loadModule(path.join(buildDir, 'lib/audit.js'));
  console.log('auditMod:', Object.keys(auditMod));
  
  // Test exportAuditLog
  const { addEvent, exportAuditLog } = auditMod;
  await addEvent({ id: 'e1', type: 'tool_use', timestamp: new Date().toISOString() });
  try {
    const exported = await exportAuditLog();
    console.log('exportAuditLog succeeded:', exported.integrity ? 'has integrity' : 'no integrity');
  } catch (err) {
    console.log('exportAuditLog failed:', err.message);
  }
}

main().catch(console.error);
