src / tools / systemTools.ts

import { exec } from "child_process";
import { promisify } from "util";
import { resolveInsideBase, targetBase } from "./constants";
import { stat, readFile, rm, writeFile } from "fs/promises";
import { join, dirname, extname } from "path";
import { existsSync } from "fs";
import { ensureDirectory } from "./constants";

const execAsync = promisify(exec);

export async function executeSystemTool(toolName: string, args: any): Promise<any> {
  switch (toolName) {
    case "getNow":
    case "getCurrentTime": {
      const now = new Date();
      return {
        success: true,
        iso: now.toISOString(),
        locale: now.toLocaleString(),
        time: now.toLocaleTimeString(),
        timestamp: Date.now(),
      };
    }

    case "getCurrentDate": {
      const today = new Date();
      return { success: true, date: today.toLocaleDateString(), isoDate: today.toISOString().slice(0, 10) };
    }

    case "terminal":
    case "wolfTerminal": {
      const cmd = args?.cmd || args?.action || "";
      const cwd = args?.cwd || targetBase;
      try {
        const response = await fetch("http://localhost:9090/api/v1", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action: "exec", data: { cmd, cwd } }),
        });
        if (response.ok) {
          const res = (await response.json()) as any;
          return {
            success: true,
            output: res.output || res.stdout || "",
            error: res.stderr || res.error || "",
            exitCode: res.exitCode ?? 0,
            system_note: `Executed via terminal server: ${cmd}`,
          };
        }
      } catch {}
      // Local fallback
      return await new Promise<any>((resolve) => {
        exec(cmd, { cwd }, (error, stdout, stderr) => {
          resolve({
            success: !error,
            output: stdout,
            error: stderr || error?.message,
            exitCode: error ? 1 : 0,
            system_note: `Executed locally: ${cmd}`,
          });
        });
      });
    }

    case "runCode": {
      const { language = "javascript", code = "" } = args;
      const tempDir = join(targetBase, "temp_scripts");
      await ensureDirectory(tempDir);
      const ext = language === "python" ? ".py" : ".js";
      const tempFile = join(tempDir, `exec_${Date.now()}${ext}`);
      await writeFile(tempFile, code, "utf-8");
      try {
        const cmd = language === "python" ? `python "${tempFile}"` : `node "${tempFile}"`;
        const { stdout, stderr } = await execAsync(cmd, { timeout: 30000 });
        await rm(tempFile, { force: true }).catch(() => {});
        return { success: true, stdout: stdout.slice(0, 5000), stderr: stderr.slice(0, 1000) };
      } catch (error: any) {
        await rm(tempFile, { force: true }).catch(() => {});
        return { success: false, error: error?.message };
      }
    }

    case "eagleEye": {
      const filePath = args?.filePath || args?.file || "";
      try {
        const fullPath = resolveInsideBase(filePath);
        const fileStat = await stat(fullPath);
        const content = await readFile(fullPath, "utf-8");
        const lines = content.split("\n");
        const suspicious = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
        const hasSuspicious = suspicious.test(content);
        const ext = extname(filePath).toLowerCase();
        
        let preview = lines.slice(0, 30).join("\n");
        if (preview.length > 2000) preview = preview.slice(0, 2000) + "\n... (truncated)";

        return {
          success: true,
          file: filePath,
          size: fileStat.size,
          lines: lines.length,
          chars: content.length,
          hasSuspicious,
          preview,
          recommendation: hasSuspicious ? "Warning: potentially malicious non-printable characters found." : "Safe to read.",
        };
      } catch (e: any) {
        return { success: false, error: e.message };
      }
    }

    case "ocrImage": {
      const imagePath = args?.imagePath || "";
      const language = args?.language || "ara+eng";
      try {
        const fullPath = resolveInsideBase(imagePath);
        if (!existsSync(fullPath)) return { success: false, error: `File not found: ${imagePath}` };

        const tesseractPaths = [
          "D:\\ocr\\Tesseract-OCR\\tesseract.exe",
          "C:\\Program Files\\Tesseract-OCR\\tesseract.exe",
          "C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe",
        ];
        let tesseractPath: string | null = null;
        for (const p of tesseractPaths) {
          if (existsSync(p)) { tesseractPath = p; break; }
        }

        if (!tesseractPath) {
          const { stdout } = await execAsync(`where tesseract 2>nul`).catch(() => ({ stdout: "" }));
          if (stdout.trim()) tesseractPath = stdout.trim().split("\n")[0];
        }

        if (!tesseractPath) return { success: false, error: "Tesseract OCR not installed or found in PATH." };

        const { stdout, stderr } = await execAsync(`"${tesseractPath}" "${fullPath}" stdout -l ${language} 2>nul`);
        if (stderr && !stderr.includes("Tesseract Open Source")) return { success: false, error: stderr };

        const text = stdout.trim();
        if (!text) return { success: false, error: "No text extracted from image." };

        return { success: true, text, language };
      } catch (e: any) {
        return { success: false, error: e.message };
      }
    }

    default:
      return null;
  }
}