#!/usr/bin/env node
// native-host/host.js - Full tool suite like opencode
const fs = require('fs');
const {execSync} = require('child_process');
const path = require('path');

process.stdin.setEncoding('utf8');
let data = '';
process.stdin.on('data', chunk => data += chunk);
process.stdin.on('end', () => {
  try {
    const req = JSON.parse(data);
    let res = {result: null, error: null};
    switch(req.tool) {
      case 'readFile':
        res.result = fs.readFileSync(req.path, 'utf8');
        break;
      case 'glob':
        const glob = require('glob');
        res.result = glob.sync(req.pattern, {cwd: req.path || process.cwd()});
        break;
      case 'grep':
        res.result = execSync(`grep -r "${req.pattern}" ${req.path || '.'}`).toString();
        break;
      case 'editFile':
        let content = fs.readFileSync(req.filePath, 'utf8');
        content = content.replace(new RegExp(req.oldString, 'g'), req.newString);
        fs.writeFileSync(req.filePath, content);
        res.result = 'Edited';
        break;
      case 'bash':
        res.result = execSync(req.cmd, {cwd: '/home/sol1/Desktop/MARKETING'}).toString();
        break;
      case 'webFetch':
        const https = require('https');
        https.get(req.url, r => {
          let body = '';
          r.on('data', c => body += c);
          r.on('end', () => process.stdout.write(JSON.stringify({result: body})));
        });
        return; // Async
      default:
        res.error = 'Unknown tool';
    }
    process.stdout.write(JSON.stringify(res));
  } catch(e) {
    process.stdout.write(JSON.stringify({error: e.message}));
  }
});