import { initializeAllContainers, registerContainers } from '@bytelyst/cosmos';
import type { ContainerConfig } from '@bytelyst/cosmos';
import { config } from './config.js';

const CONTAINER_DEFS: Record<string, ContainerConfig> = {
  notes: { partitionKeyPath: '/workspaceId' },
  workspaces: { partitionKeyPath: '/userId' },
  note_relationships: { partitionKeyPath: '/workspaceId' },
  note_tasks: { partitionKeyPath: '/workspaceId' },
  note_artifacts: { partitionKeyPath: '/workspaceId' },
  note_agent_actions: { partitionKeyPath: '/workspaceId' },
};

export async function initCosmosIfNeeded(): Promise<void> {
  registerContainers(CONTAINER_DEFS);

  const shouldInit = config.NODE_ENV !== 'production' || process.env.COSMOS_AUTO_INIT === 'true';
  if (!shouldInit || config.DB_PROVIDER === 'memory') {
    return;
  }

  try {
    await initializeAllContainers();
    process.stdout.write('[bytelyst-notes-backend] Cosmos containers ensured\n');
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    process.stderr.write(`[bytelyst-notes-backend] Cosmos init failed: ${msg}\n`);
  }
}
