/**
 * WorkspaceAPI Tool — local filesystem + remote fallback for VL Workspace operations
 *
 * When a LocalWorkspace is provided, all file/doc operations use the local filesystem.
 * When not available (or workflowMode='remote'), falls back to the remote VL Platform API.
 *
 * Actions: createFile, listFile, readFile, writeFile, deleteFile,
 *          createFiles, readFiles, writeFiles, deleteFiles,
 *          createDoc, readDoc, writeDoc, deleteDoc, listDoc
 */

/**
 * @param {Object} config - VL-Code configuration
 * @param {import('../engine/local-workspace.js').LocalWorkspace} [localWorkspace] - Local workspace instance
 */
export function createWorkspaceAPITool(config, localWorkspace = null) {
  const baseUrl = config.workspaceApiUrl || 'https://editor.visuallogic.ai/ih5/editor/workspace';
  const useLocal = localWorkspace && config.workflowMode !== 'remote';

  return {
    description: `Interact with VL Workspace for file/document management.
Mode: ${useLocal ? 'LOCAL (filesystem-backed, zero latency)' : 'REMOTE (cloud API)'}
Actions: createFile, listFile, readFile, writeFile, deleteFile, createFiles, readFiles, writeFiles, deleteFiles, createDoc, listDoc, readDoc, writeDoc, deleteDoc.`,
    parameters: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: [
            'createFile', 'listFile', 'readFile', 'writeFile', 'deleteFile',
            'createFiles', 'readFiles', 'writeFiles', 'deleteFiles',
            'createDoc', 'listDoc', 'readDoc', 'writeDoc', 'deleteDoc',
          ],
          description: 'API action to perform',
        },
        gid: {
          type: 'string',
          description: 'Group/workspace ID',
        },
        path: {
          type: 'string',
          description: 'File or document path',
        },
        paths: {
          type: 'array',
          items: { type: 'string' },
          description: 'Multiple file paths (for batch operations)',
        },
        content: {
          type: 'string',
          description: 'File content (for write operations)',
        },
        files: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              path: { type: 'string' },
              content: { type: 'string' },
            },
          },
          description: 'Multiple files (for batch write)',
        },
        version: {
          type: 'string',
          description: 'Specific version to read (optional)',
        },
        shared: {
          type: 'boolean',
          description: 'Whether doc is shared (for doc operations)',
        },
      },
      required: ['action'],
    },
    execute: async (input) => {
      if (useLocal) {
        return executeLocal(localWorkspace, input);
      }
      return executeRemote(baseUrl, input);
    },
  };
}

/**
 * Execute an action via the local filesystem workspace.
 */
async function executeLocal(workspace, input) {
  const { action, ...params } = input;

  try {
    let result;
    switch (action) {
      case 'createFile':
        result = await workspace.createFile(params);
        break;
      case 'listFile':
        result = await workspace.listFile(params);
        break;
      case 'readFile':
        result = await workspace.readFile(params);
        break;
      case 'writeFile':
        result = await workspace.writeFile(params);
        break;
      case 'deleteFile':
        result = await workspace.deleteFile(params);
        break;
      case 'createFiles':
        result = await workspace.createFiles(params);
        break;
      case 'readFiles':
        result = await workspace.readFiles(params);
        break;
      case 'writeFiles':
        result = await workspace.writeFiles(params);
        break;
      case 'deleteFiles':
        result = await workspace.deleteFiles(params);
        break;
      case 'createDoc':
        result = await workspace.createDoc(params);
        break;
      case 'listDoc':
        result = await workspace.listDoc(params);
        break;
      case 'readDoc':
        result = await workspace.readDoc(params);
        break;
      case 'writeDoc':
        result = await workspace.writeDoc(params);
        break;
      case 'deleteDoc':
        result = await workspace.deleteDoc(params);
        break;
      default:
        return `Unknown action: ${action}`;
    }

    if (result && typeof result === 'object') {
      return JSON.stringify(result, null, 2);
    }
    return `${action}: Success`;
  } catch (err) {
    return `WorkspaceAPI (local) error: ${err.message}`;
  }
}

/**
 * Execute an action via the remote VL Platform API (fallback).
 */
async function executeRemote(baseUrl, input) {
  const { action, ...params } = input;
  const url = `${baseUrl}/${action}`;

  try {
    const body = {};
    if (params.gid) body.gid = params.gid;
    if (params.path) body.path = params.path;
    if (params.paths) body.paths = params.paths;
    if (params.content !== undefined) body.content = params.content;
    if (params.files) body.files = params.files;
    if (params.version) body.version = params.version;
    if (params.shared !== undefined) body.shared = params.shared;

    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      return `API error: ${response.status} ${response.statusText}`;
    }

    const text = await response.text();
    if (!text || text.trim() === '') {
      return `${action}: Success (no return value)`;
    }

    try {
      const json = JSON.parse(text);
      return JSON.stringify(json, null, 2);
    } catch {
      return text;
    }
  } catch (err) {
    return `WorkspaceAPI error: ${err.message}`;
  }
}
