import { mkdir } from 'fs/promises';
import { existsSync } from 'fs';
import { join, resolve } from 'path';
import { getConfig, updateConfig, getAgentRoot } from './config.mjs';
import {
  addWorkspace, getWorkspace, listWorkspacesFromDb,
  setActiveWorkspace as dbSetActiveWorkspace, getActiveWorkspace, deleteWorkspaceFromDb
} from './db.mjs';

const WORKSPACES_BASE = join(getAgentRoot(), 'workspaces');

export async function initWorkspaces() {
  const config = getConfig();
  // Default workspace root: use workspaces/<id> pattern (not the parent workspaceRoot)
  const defaultRoot = join(WORKSPACES_BASE, 'default');

  const existing = getWorkspace('default');
  if (!existing) {
    addWorkspace('default', 'Default', defaultRoot, 'The default workspace');
    dbSetActiveWorkspace('default');
  } else if (!existsSync(existing.root_path)) {
    // Fix stale/wrong path (e.g. Windows path on macOS, or moved install)
    addWorkspace('default', existing.name, defaultRoot, existing.description || 'The default workspace');
    console.log(`[workspace-manager] Updated default workspace path: ${existing.root_path} → ${defaultRoot}`);
  }

  await mkdir(WORKSPACES_BASE, { recursive: true });
  await mkdir(defaultRoot, { recursive: true });
  console.log('[workspace-manager] Workspaces initialized');
}

export async function createWorkspace(name, description = '') {
  const id = slugify(name);
  if (getWorkspace(id)) throw new Error(`Workspace "${id}" already exists`);

  const rootPath = join(WORKSPACES_BASE, id);
  await mkdir(rootPath, { recursive: true });

  addWorkspace(id, name, rootPath, description);
  return getWorkspace(id);
}

export function switchWorkspace(id) {
  const ws = getWorkspace(id);
  if (!ws) throw new Error(`Workspace "${id}" not found`);
  dbSetActiveWorkspace(id);
  updateConfig({ activeWorkspace: id });
  console.log(`[workspace-manager] Switched to workspace: ${id}`);
  return ws;
}

export function getActiveWorkspaceId() {
  const active = getActiveWorkspace();
  return active?.id || 'default';
}

export function getActiveWorkspacePath() {
  const active = getActiveWorkspace();
  return active?.root_path || getConfig().workspaceRoot || join(getAgentRoot(), 'workspace');
}

export function listAllWorkspaces() {
  return listWorkspacesFromDb();
}

export function deleteWorkspace(id) {
  if (id === 'default') throw new Error('Cannot delete the default workspace');
  const active = getActiveWorkspace();
  if (active?.id === id) {
    switchWorkspace('default');
  }
  deleteWorkspaceFromDb(id);
  // Note: does NOT delete the physical directory (data preservation)
}

export function getWorkspacePath(id) {
  const ws = getWorkspace(id);
  return ws?.root_path || null;
}

function slugify(text) {
  return String(text || '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
    .slice(0, 40) || 'workspace';
}
