/**
 * FreeBSD Jail runtime for Clawdie.
 *
 * Key properties:
 * - No "orphaned" state (stopped = removed)
 * - No daemon needed
 * - Nullfs mounts can persist after crash
 * - Use /etc/jail.conf for persistence
 */
import { execSync } from 'child_process';

import { logger } from './logger.js';

/** Returns CLI args for a readonly nullfs bind mount. */
export function readonlyMountArgs(
  hostPath: string,
  jailPath: string,
): string[] {
  return ['-o', 'ro', hostPath, jailPath];
}

/** Returns the shell command to stop a jail by name. */
export function stopJail(name: string): string {
  return `service jail stop ${name}`;
}

/** Jails need no daemon. No-op kept for call-site compatibility. */
export function ensureJailRunning(): void {
  logger.debug('Using FreeBSD jail runtime (no daemon needed)');
}

/** Check for stale jail artifacts from previous runs. */
export function cleanupStaleJails(): void {
  logger.debug('Checking for stale FreeBSD jail artifacts...');

  // Nullfs mounts can persist if jail crashed before unmounting
  try {
    const mounts = execSync('mount | grep clawdie-cp || true', {
      encoding: 'utf-8',
      stdio: ['pipe', 'pipe', 'pipe'],
    });

    if (mounts.trim()) {
      const mountLines = mounts.trim().split('\n').filter(Boolean);
      logger.warn(
        {
          count: mountLines.length,
          mounts: mountLines,
        },
        'Found stale nullfs mounts from previous jail session. ' +
          'This can happen if the jail crashed. ' +
          'Run manually if needed: umount -f /jails/clawdie-cp/home/clawdie/*',
      );

      for (const line of mountLines) {
        logger.debug({ mount: line }, 'Stale mount detected');
      }
    } else {
      logger.debug('No stale jail mounts found');
    }
  } catch (error) {
    logger.debug({ error }, 'No stale mounts (or mount command failed)');
  }

  // Running jails with our prefix shouldn't exist at startup
  try {
    const jlsOutput = execSync('jls -n 2>/dev/null || true', {
      encoding: 'utf-8',
    });

    if (jlsOutput.includes('clawdie-cp-')) {
      const lines = jlsOutput
        .split('\n')
        .filter((l) => l.includes('clawdie-cp-'));
      logger.warn(
        { jails: lines },
        'Found unexpected running jails from previous session. ' +
          'Manual cleanup may be needed: service jail stop <name>',
      );
    }
  } catch {
    // jls not available or no jails running
  }
}
