import path from 'path';
import { execFileSync } from 'child_process';

import { RUNTIME_STATE_DIR } from './config.js';

export function getTenantSystemdSlice(tenantId: string | undefined): string | null {
  if (!tenantId) return null;

  try {
    const entry = execFileSync('getent', ['passwd', tenantId], {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
    if (!entry) return null;
    const parts = entry.split(':');
    const uid = Number(parts[2]);
    if (!Number.isInteger(uid) || uid < 0) return null;
    return `user-${uid}.slice`;
  } catch {
    return null;
  }
}

export function getComposeCgroupOverridePath(
  composePath: string,
  tenantId: string,
): string {
  const appDirName = path.basename(path.dirname(composePath));
  const composeFileName = path.basename(composePath);
  return path.join(
    RUNTIME_STATE_DIR,
    'compose-overrides',
    tenantId,
    `${appDirName}.${composeFileName}.nanoclaw.cgroup-parent.override.yml`,
  );
}

export function buildComposeCgroupOverride(
  serviceNames: string[],
  cgroupParent: string,
): string {
  const lines = ['services:'];
  for (const serviceName of serviceNames) {
    lines.push(`  ${serviceName}:`);
    lines.push(`    cgroup_parent: ${cgroupParent}`);
    lines.push(`    cpu_shares: 256`); // Low CPU priority for app containers vs agent containers
  }
  return lines.join('\n') + '\n';
}
