/**
 * WorkspaceManager Tool — create, switch, and list workspaces from AI conversation
 *
 * Actions:
 *   create  — scaffold a new VL project and optionally switch to it
 *   switch  — switch active workspace (file tree syncs automatically)
 *   list    — list all registered workspaces
 *
 * The tool calls the server's own HTTP API so that all side-effects
 * (file tree refresh, SSE broadcast, tab management) happen automatically.
 */
import fs from 'fs';
import path from 'path';
import os from 'os';

export function createWorkspaceManagerTool(config) {
  return {
    name: 'WorkspaceManager',
    description: `Create, switch, or list workspaces. The left-side file tree updates automatically after create/switch.
Actions:
  create  — create a new VL project directory with standard structure, add to workspace list, optionally switch to it
  switch  — switch active workspace to an existing directory (file tree + tabs sync)
  list    — list all registered workspaces`,
    parameters: {
      type: 'object',
      properties: {
        action: {
          type: 'string',
          enum: ['create', 'switch', 'list'],
          description: 'Action to perform',
        },
        projectName: {
          type: 'string',
          description: '(create) Project name — PascalCase, English only',
        },
        parentDir: {
          type: 'string',
          description: '(create) Parent directory. Default: ~/Documents/VLProjects. Use ~/Documents/VLProjects/_tests for test projects.',
        },
        dirPath: {
          type: 'string',
          description: '(switch) Absolute path to the workspace directory to switch to',
        },
        autoSwitch: {
          type: 'boolean',
          description: '(create) Automatically switch to the new workspace after creation. Default: true',
        },
      },
      required: ['action'],
    },
    execute: async (params) => {
      const { action } = params;

      try {
        const serverBase = getServerBase(config);
        switch (action) {
          case 'create':
            return await handleCreate(params, serverBase);
          case 'switch':
            return await handleSwitch(params, serverBase);
          case 'list':
            return await handleList(serverBase);
          default:
            return `Unknown action: ${action}. Use create, switch, or list.`;
        }
      } catch (err) {
        return `WorkspaceManager error: ${err.message}`;
      }
    },
  };
}

function getServerBase(config) {
  return `http://localhost:${config.port || 3300}`;
}

async function handleCreate(params, serverBase) {
  const { projectName, parentDir, autoSwitch = true } = params;
  if (!projectName) return 'Error: projectName is required for create action.';

  // Validate PascalCase English-only
  if (!/^[A-Z][A-Za-z0-9]*$/.test(projectName)) {
    return `Error: projectName must be PascalCase English-only (e.g. "MyProject"). Got: "${projectName}"`;
  }

  const base = parentDir
    ? parentDir.replace(/^~/, os.homedir())
    : path.join(os.homedir(), 'Documents', 'VLProjects');

  const projDir = path.join(base, projectName);

  // Check if already exists
  if (fs.existsSync(projDir) && fs.readdirSync(projDir).length > 0) {
    return `Warning: Directory already exists and is non-empty: ${projDir}\nUse 'switch' action to open it, or choose a different name.`;
  }

  // Call server API to create
  const resp = await fetch(`${serverBase}/api/workspaces/create-project`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ projectName, parentDir: base }),
  });

  if (!resp.ok) {
    const err = await resp.json().catch(() => ({}));
    return `Create failed (${resp.status}): ${err.error || resp.statusText}`;
  }

  const result = await resp.json();
  const createdPath = result.path;

  // Auto-switch if requested
  if (autoSwitch) {
    const switchResult = await handleSwitch({ dirPath: createdPath }, serverBase);
    return `Created project "${projectName}" at ${createdPath}\n${switchResult}`;
  }

  return `Created project "${projectName}" at ${createdPath}\nUse action "switch" with dirPath="${createdPath}" to open it.`;
}

async function handleSwitch(params, serverBase) {
  const { dirPath } = params;
  if (!dirPath) return 'Error: dirPath is required for switch action.';

  const resolvedPath = dirPath.replace(/^~/, os.homedir());

  if (!fs.existsSync(resolvedPath)) {
    return `Error: Directory does not exist: ${resolvedPath}`;
  }

  const resp = await fetch(`${serverBase}/api/workspaces/switch`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ dirPath: resolvedPath }),
  });

  if (!resp.ok) {
    const err = await resp.json().catch(() => ({}));
    return `Switch failed (${resp.status}): ${err.error || resp.statusText}`;
  }

  const result = await resp.json();
  return `Switched to workspace: ${result.workDir}\nVL Project: ${result.isVL ? 'Yes' : 'No'}\nFile tree updated — left sidebar now shows the new workspace.`;
}

async function handleList(serverBase) {
  const resp = await fetch(`${serverBase}/api/workspaces`);
  if (!resp.ok) return `List failed (${resp.status})`;

  const list = await resp.json();
  if (!list.length) return 'No workspaces registered.';

  const lines = list.map((w, i) =>
    `${i + 1}. ${w.name} — ${w.path}${w.addedAt ? ` (added ${w.addedAt.slice(0, 10)})` : ''}`
  );
  return `Workspaces (${list.length}):\n${lines.join('\n')}`;
}
