src / toolsProvider.ts

// ============================================================
// toolsProvider.ts — TEACHER'S EDITION (v2.1) bye bye mr. schema
// ============================================================

import { tool, Tool } from "@lmstudio/sdk";
import { z } from "zod";
import { executeFileTool } from "./tools/fileTools";
import { executeMemoryTool } from "./tools/memoryTools";
import { executeSystemTool } from "./tools/systemTools";
import { executeWebTool } from "./tools/webTools";
import { executeExcelTool } from "./tools/excelTools";

// ============================================================
// SERVER REGISTRY — 4 Cognitive Arms
// ============================================================
const SERVERS = {
  core: "http://127.0.0.1:5075",
  code: "http://127.0.0.1:4041",
  terminal: "http://127.0.0.1:9090",
  memory: "http://127.0.0.1:5077",
} as const;

type ServerName = keyof typeof SERVERS;

// ============================================================
// TOOL ALIASES
// ============================================================
const TOOL_ALIASES: Record<string, string> = {
  getNow: "getTime",
  getCurrentTime: "getTime",
  getCurrentDate: "getDate",
  deleteFile: "moveToTrash",
  listFolder: "listFiles",
  appendFile: "appendToFile",
  runCode: "runPythonScript",
  terminal: "exec",
  wolfTerminal: "exec",
  semanticMemory: "semanticSearch",
  memory_search: "semanticSearch",
  read_file: "readFile",
  write_file: "writeFile",
  list_folder: "listFiles",
};

// ============================================================
// HEAVY / LONG-RUNNING TOOLS (10 minutes timeout)
// ============================================================
const HEAVY_TOOLS = new Set([
  "writeFile",
  "write_file",
  "appendFile",
  "appendToFile",
  "searchFiles",
  "runCode",
  "runPythonScript",
  "exec",
  "terminal",
  "wolfTerminal",
  "ocrImage",
]);

function getTimeoutForTool(toolName: string): number {
  return HEAVY_TOOLS.has(toolName) ? 600_000 : 60_000;
}

// ============================================================
// CATALOG CACHE — Dynamic discovery across the 4 servers
// ============================================================
const cachedCatalog: Record<ServerName, string[]> = {
  core: [],
  code: [],
  terminal: [],
  memory: [],
};

const cachedToolToServer = new Map<string, ServerName>();
let catalogPromise: Promise<void> | null = null;

function extractToolNames(payload: any): string[] {
  if (!payload) return [];
  const rawList = Array.isArray(payload)
    ? payload
    : Array.isArray(payload.tools)
    ? payload.tools
    : Array.isArray(payload.data)
    ? payload.data
    : [];

  return rawList
    .map((item: any) => (typeof item === "string" ? item : item?.name || item?.tool || item?.id))
    .filter((name: any): name is string => typeof name === "string" && name.length > 0);
}

async function fetchServerTools(serverName: ServerName, baseUrl: string): Promise<string[]> {
  const endpoints = [`${baseUrl}/tools`, `${baseUrl}/catalog`, `${baseUrl}/api/tools`];
  for (const url of endpoints) {
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(4000) });
      if (!res.ok) continue;
      const data = await res.json();
      const names = extractToolNames(data);
      if (names.length > 0) return names;
    } catch {
      // Try next endpoint
    }
  }
  return [];
}

async function refreshCatalog(): Promise<void> {
  if (catalogPromise) return catalogPromise;

  catalogPromise = (async () => {
    try {
      const entries = Object.entries(SERVERS) as [ServerName, string][];
      const results = await Promise.all(
        entries.map(async ([serverName, url]) => {
          const tools = await fetchServerTools(serverName, url);
          return [serverName, tools] as const;
        })
      );

      for (const [serverName, tools] of results) {
        if (tools.length > 0) {
          cachedCatalog[serverName] = tools;
          for (const t of tools) {
            cachedToolToServer.set(t, serverName);
          }
        }
      }

      // Ensure core default routes exist even if a catalog endpoint wasn't exposed
      if (!cachedToolToServer.has("exec")) cachedToolToServer.set("exec", "terminal");
      if (!cachedToolToServer.has("semanticSearch")) cachedToolToServer.set("semanticSearch", "memory");
    } finally {
      catalogPromise = null;
    }
  })();

  return catalogPromise;
}

function getServerForTool(toolName: string): ServerName | null {
  if (cachedToolToServer.has(toolName)) {
    return cachedToolToServer.get(toolName) || null;
  }
  if (toolName === "exec" || toolName === "terminal" || toolName === "wolfTerminal") {
    return "terminal";
  }
  if (toolName === "semanticSearch" || toolName === "semanticMemory") {
    return "memory";
  }
  return null;
}

// ============================================================
// 🎨 SMART RESULT FORMATTER (The Presentation Layer)
// ============================================================
function formatResult(result: any): string {
  if (!result) return "✅ Done (no output)";

  // 1. الأخطاء + التلميح الذكي لتصحيح مسار النموذج
  if (result.success === false || result.error) {
    const hint = result.hint ? `\n💡 Hint: ${result.hint}` : "";
    return `❌ Error: ${result.error || "Unknown error"}${hint}`;
  }

  // فك تغليف النتيجة الأساسية من السيرفرات
  const core = result.result || result;

  // 2. قراءة الملفات أو الجلسات الخام (readFile / readRawSession)
  if (core.content && typeof core.content === "string") {
    return core.content;
  }

  // 3. نتائج البحث (بحث الذاكرة السيميائي + بحث الملفات)
  if (Array.isArray(core.results)) {
    if (core.results.length === 0) return "No results found.";
    const limit = 25;
    const list = core.results
      .slice(0, limit)
      .map((r: any) => {
        if (typeof r === "string") return `- ${r}`;

        // أ) نتائج الذاكرة السيميائية (مع سند الملكية للتعمق)
        if (r.session_id || r.title || r.summary || r.similarity) {
          const title = r.title || r.session_id || "Memory Session";
          const score = r.similarity ? ` (${Math.round(r.similarity * 100)}%)` : "";
          const idTag = r.session_id ? ` | ID: ${r.session_id}` : "";
          const fileTag = r.raw_file || r.file_path ? ` | File: ${r.raw_file || r.file_path}` : "";
          const summary = r.summary ? String(r.summary).replace(/\n/g, " ").slice(0, 180) + "..." : "";
          return `- [${title}]${score}${idTag}${fileTag}${summary ? `\n  ${summary}` : ""}`;
        }

        // ب) نتائج بحث الملفات (تُظهر المسار الكامل عشان النموذج يقدر يقرأه فوراً)
        const fullPath = r.fullPath || r.path || r.file || r.name;
        return `- ${fullPath || JSON.stringify(r).slice(0, 150)}`;
      })
      .join("\n");

    const note = core.results.length > limit ? `\n...and ${core.results.length - limit} more.` : "";
    return `Found ${core.total || core.results.length} results:\n${list}${note}`;
  }

  // 4. قوائم المجلدات (listFiles / listFolder) لو راجعة في مصفوفة files أو items
  const items = core.files || core.items || core.entries;
  if (Array.isArray(items)) {
    if (items.length === 0) return "Directory is empty.";
    return items
      .slice(0, 50)
      .map((f: any) => {
        if (typeof f === "string") return `- ${f}`;
        const icon = f.isDirectory || f.type === "directory" || f.type === "folder" ? "📁" : "📄";
        return `${icon} ${f.name || f.path}`;
      })
      .join("\n");
  }

  // 5. الوقت والتاريخ (getTime / getDate)
  if (core.display && typeof core.display === "string") {
    return core.display;
  }

  // 6. أي كائن تاني (تنظيف الميتا داتا الزيادة)
  if (typeof core === "object") {
    const IGNORE = new Set(["success", "requestId", "executedAt", "source", "howl", "status", "method"]);
    const lines: string[] = [];
    for (const [k, v] of Object.entries(core)) {
      if (v === null || v === undefined || IGNORE.has(k)) continue;
      let val = typeof v === "object" ? JSON.stringify(v) : String(v);
      if (val.length > 250) val = val.slice(0, 250) + "... (truncated)";
      lines.push(`${k}: ${val}`);
    }
    return lines.length ? lines.join("\n") : "✅ Done";
  }

  return String(core);
}

// ============================================================
// EXECUTE VIA SERVER
// ============================================================
async function executeViaServer(toolName: string, params: any): Promise<any | null> {
  const serverName = getServerForTool(toolName);
  if (!serverName) return null;

  const timeoutMs = getTimeoutForTool(toolName);

  try {
    const res = await fetch(`${SERVERS[serverName]}/tool/${encodeURIComponent(toolName)}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params || {}),
      signal: AbortSignal.timeout(timeoutMs),
    });
    if (!res.ok) return null;

    const data = (await res.json()) as any;
    if (data.status === "success" || data.success) {
      return { success: true, ...data, source: `server_${serverName}` };
    }
  } catch (err) {
    const error = err as Error;
    if (error.name === "TimeoutError" || error.name === "AbortError") {
      return {
        success: false,
        error: `Request timed out after ${Math.round(timeoutMs / 1000)}s on local server '${serverName}' for tool '${toolName}'.`,
        hint: "The task may still be running or may have already completed in the background on the local server. Verify the target file/output before re-running.",
      };
    }
    console.warn(`[Server] ${serverName}/${toolName}: ${error.message}`);
  }
  return null;
}

// ============================================================
// EXECUTE LOCALLY — Fallback
// ============================================================
async function executeLocally(toolName: string, params: any): Promise<any | null> {
  let result = await executeSystemTool(toolName, params);
  if (result) return result;

  result = await executeFileTool(toolName, params);
  if (result) return result;

  result = await executeMemoryTool(toolName, params);
  if (result) return result;

  result = await executeWebTool(toolName, params);
  if (result) return result;

  result = await executeExcelTool(toolName, params);
  if (result) return result;

  return null;
}

// ============================================================
// EXECUTE TOOL — Main dispatcher
// ============================================================
export async function executeTool(rawToolName: string, args: any = {}): Promise<any> {
  const toolName = TOOL_ALIASES[rawToolName] || rawToolName;

  // Lazy init catalog if empty
  if (cachedToolToServer.size === 0) {
    try {
      await refreshCatalog();
    } catch (err) {
      console.warn("[executeTool] catalog refresh failed:", (err as Error).message);
    }
  }

  // 1. Try local servers (try mapped alias first, then raw name if different)
  const serverResult = await executeViaServer(toolName, args);
  if (serverResult) return serverResult;

  if (toolName !== rawToolName) {
    const rawServerResult = await executeViaServer(rawToolName, args);
    if (rawServerResult) return rawServerResult;
  }

  // 2. Local fallback (try mapped alias first, then raw name to match local switch cases)
  const localResult = await executeLocally(toolName, args);
  if (localResult) return localResult;

  if (toolName !== rawToolName) {
    const rawLocalResult = await executeLocally(rawToolName, args);
    if (rawLocalResult) return rawLocalResult;
  }

  // Clear error guiding the model
  const availableTools =
    cachedToolToServer.size > 0
      ? [...cachedToolToServer.keys()].slice(0, 12).join(", ")
      : "none (servers unreachable)";

  return {
    success: false,
    error: `Unknown tool: ${rawToolName}`,
    hint: `Sample available tools: ${availableTools}...`,
    servers: SERVERS,
  };
}

// ============================================================
// TOOLS PROVIDER — Single Gateway (wolfGateway)
// ============================================================
export async function toolsProvider(): Promise<Tool[]> {
  try {
    await refreshCatalog();
  } catch {
    console.warn("[toolsProvider] Catalog refresh failed — gateway will still work");
  }

  return [
    tool({
      name: "wolfGateway",
      description: `## SYSTEM DIRECTIVE
You are a smart AI assistant working in a development environment called cognitive castle. You have ONE function tool which can handle over 200 sub-tools, called "wolfGateway". Just wrap any of them inside "wolfGateway".
NEVER call sub-tools directly. ALWAYS wrap them inside "wolfGateway".
Format: {"tool": "<tool_name>", "args": {<arguments>}}

## TOOL CATALOG & USAGE
| Tool Name | Purpose | Exact Call Format (JSON) |
| :--- | :--- | :--- |
| **getTime** | Get current date & time (12h) | {"tool": "getTime", "args": {}} |
| **getDate** | Get current date only | {"tool": "getDate", "args": {}} |
| **readFile** | Read a text file | {"tool": "readFile", "args": {"path": "D:/bido/2026/file.txt"}} |
| **writeFile** | Write to a file | {"tool": "writeFile", "args": {"path": "D:/bido/2026/file.txt", "content": "text"}} |
| **appendToFile** | Append to a file | {"tool": "appendToFile", "args": {"path": "D:/bido/2026/file.txt", "content": "text"}} |
| **listFiles** | List dir contents | {"tool": "listFiles", "args": {"path": "D:/bido/2026"}} |
| **searchFiles** | Find files by name/content | {"tool": "searchFiles", "args": {"path": "D:/bido/2026", "query": "name", "type": "name"}} |
| **exec** | Full shell via terminal server (supports Git Bash / Unix & Windows shell commands, git, scripts, grep/find, system ops; pass cmd & optional cwd) | {"tool": "exec", "args": {"cmd": "ls -la", "cwd": "D:/bido/2026"}} |
| **searchWeb** | Search internet | {"tool": "searchWeb", "args": {"query": "news", "maxResults": 5}} |
| **semanticSearch** | Search semantic memory | {"tool": "semanticSearch", "args": {"query": "topic", "limit": 2}} |

## STRICT RULES
1. "tool" must be the FIRST key. "args" must be the SECOND key.
2. If no arguments are needed, use {}.
3. NEVER use the word "params". ALWAYS use "args".
4. DO NOT explain the JSON to the user. Execute it and give the final answer.`,
      parameters: {
        tool: z.string().describe("Exact tool name from the catalog. MUST be top-level, NOT inside args."),
        args: z
          .record(z.any())
          .optional()
          .describe("Tool arguments as a flat JSON object. Omit or use {} if the tool takes none."),
      },
      implementation: async ({ tool: toolName, args }) => {
        let parsedArgs = args;
        if (typeof args === "string") {
          try {
            parsedArgs = JSON.parse(args);
          } catch {
            parsedArgs = {};
          }
        }
        const result = await executeTool(toolName, parsedArgs || {});
        return formatResult(result);
      },
    }),
  ];
}

// ============================================================
// BOOT — prime the catalog at module load
// ============================================================
refreshCatalog().catch((err) =>
  console.warn("[BOOT] initial catalog load failed:", (err as Error).message)
);