'use strict';

function normalizeLiveStatus(status) {
  const text = String(status || '').toLowerCase().replace(/[-\s]+/g, '_');
  if (!text) return '';
  if (text === 'busy' || text === 'active' || text === 'working' || text === 'thinking') return 'running';
  if (text === 'restoring' || text === 'resuming' || text === 'restore_starting' || text === 'restarting') return 'resuming';
  if (text === 'waiting_for_input') return 'waiting_input';
  if (['running', 'resuming', 'waiting', 'waiting_input', 'idle', 'exited'].includes(text)) return text;
  return '';
}

function activeSessionQuiescence(status, opts = {}) {
  const normalized = normalizeLiveStatus(status);
  if (opts.waitingForInput || normalized === 'waiting' || normalized === 'waiting_input') {
    return {
      ok: false,
      status: normalized || 'waiting_input',
      reason: 'Resolve the active session prompt before syncing from main.',
    };
  }
  if (opts.pendingApproval) {
    return {
      ok: false,
      status: normalized || 'waiting_input',
      reason: 'Resolve the active session approval before syncing from main.',
    };
  }
  if (normalized !== 'idle') {
    return {
      ok: false,
      status: normalized || 'unknown',
      reason: 'Wait for the active session to become idle before syncing from main.',
    };
  }
  return {
    ok: true,
    status: 'idle',
    reason: 'Active session is idle.',
  };
}

function activeSyncWorktreePolicy(wt, quiescence, opts = {}) {
  if (!wt || wt.isMain) return { ok: false, reason: 'Primary checkout cannot be synced this way.' };
  if (!quiescence || !quiescence.ok) {
    return {
      ok: false,
      status: quiescence && quiescence.status ? quiescence.status : 'unknown',
      reason: quiescence && quiescence.reason
        ? quiescence.reason
        : 'Wait for the active session to become idle before syncing from main.',
    };
  }
  if (opts.strategy && opts.strategy !== 'merge') {
    return { ok: false, status: quiescence.status, reason: 'Active sessions can only sync with merge, not rebase.' };
  }
  if (wt.isGhost || wt.state === 'ghost') {
    return { ok: false, status: quiescence.status, reason: 'Prune or recover this ghost worktree before syncing from main.' };
  }
  if (!wt.branch || wt.branch === 'HEAD' || wt.state === 'detached') {
    return { ok: false, status: quiescence.status, reason: 'Recover this worktree onto a branch before syncing from main.' };
  }
  const trackedDirty = wt.trackedDirtyFiles != null
    ? Number(wt.trackedDirtyFiles || 0)
    : Math.max(0, Number(wt.dirtyFiles || 0) - Number(wt.untrackedFiles || 0));
  if (trackedDirty > 0) {
    return { ok: false, status: quiescence.status, reason: 'Commit or stash tracked dirty files before syncing from main.' };
  }
  if ((wt.ahead || 0) > 0 || wt.state === 'diverged') {
    return {
      ok: false,
      status: quiescence.status,
      reason: 'Close or pause the active session before syncing a diverged branch.',
    };
  }
  if ((wt.behind || 0) <= 0 || wt.state !== 'behind') {
    return { ok: false, status: quiescence.status, reason: 'This active worktree is not behind main.' };
  }
  return {
    ok: true,
    status: quiescence.status,
    reason: 'Active session is idle and tracked files are clean; sync can proceed with confirmation.',
  };
}

module.exports = {
  normalizeLiveStatus,
  activeSessionQuiescence,
  activeSyncWorktreePolicy,
};
