import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { ServiceConfig, AutoFixResult } from './types.js';
import type { Logger } from './logger.js';
import { getState } from './state.js';

export function attemptAutoFix(
  service: ServiceConfig,
  logger: Logger,
): AutoFixResult {
  const state = getState(service.id);

  if (service.autoFix === 'none' || !service.autoFix) {
    return { attempted: false, action: 'none', success: false, output: '' };
  }

  const pm2Name = service.pm2Name;
  if (!pm2Name) {
    return { attempted: false, action: 'none', success: false, output: 'No PM2 name configured' };
  }

  // Attempt 1: simple PM2 restart
  // Attempt 2: clear .next/cache (for Next.js) + PM2 restart
  const isSecondAttempt = state.autoFixAttempts >= 1;
  const shouldClearCache =
    isSecondAttempt && service.autoFix === 'clear-next-cache' && service.autoFixCwd;

  let action = `pm2 restart ${pm2Name}`;

  try {
    if (shouldClearCache) {
      const cachePath = path.join(service.autoFixCwd!, '.next', 'cache');
      if (fs.existsSync(cachePath)) {
        fs.rmSync(cachePath, { recursive: true, force: true });
        logger.info(`Cleared .next/cache for ${service.id}`, { path: cachePath });
        action = `rm -rf .next/cache && pm2 restart ${pm2Name}`;
      }
    }

    const output = execSync(`pm2 restart ${pm2Name}`, {
      timeout: 30_000,
      encoding: 'utf-8',
    });

    logger.info(`Auto-fix executed for ${service.id}`, { action, output: output.trim() });

    return {
      attempted: true,
      action,
      success: true,
      output: output.trim().slice(0, 500),
    };
  } catch (err) {
    const errorMsg = err instanceof Error ? err.message : String(err);
    logger.error(`Auto-fix failed for ${service.id}`, { action, error: errorMsg });

    return {
      attempted: true,
      action,
      success: false,
      output: errorMsg.slice(0, 500),
    };
  }
}
