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

/**
 * Resolve the workspaces base directory from config.workspaceRoot.
 * This ensures packaged Electron apps store workspaces in userData
 * (survives app updates) rather than inside the .app bundle.
 */
function getWorkspacesBase() {
  return getConfig().workspaceRoot;
}

export async function initWorkspaces() {
  const base = getWorkspacesBase();
  const defaultRoot = join(base, 'default');

  const existing = getWorkspace('default');
  if (!existing) {
    addWorkspace('default', 'Default', defaultRoot, 'The default workspace');
    dbSetActiveWorkspace('default');
  } else if (!existsSync(existing.root_path) || existing.root_path.includes('.app/') || existing.root_path.includes('.app\\')) {
    // Fix stale/wrong path (e.g. inside .app bundle, 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(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(getWorkspacesBase(), 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 || getWorkspacesBase();
}

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';
}
