'use strict';

const fs = require('fs');
const path = require('path');

function pathExists(p) {
  if (!p || typeof p !== 'string') return false;
  try { return fs.existsSync(path.resolve(p)); } catch { return false; }
}

function firstExistingPath(paths) {
  for (const p of paths) {
    if (pathExists(p)) return path.resolve(p);
  }
  return '';
}

function sessionLabel(session) {
  return session?.label || session?.meta?.label || '';
}

function buildSessionPathCandidates(session, prefix) {
  if (!session) return [];
  const label = sessionLabel(session);
  return [
    { cwd: session.worktree_path, source: `${prefix}_worktree`, sessionId: session.id || null, label },
    { cwd: session.cwd, source: `${prefix}_session`, sessionId: session.id || null, label },
    { cwd: session.meta?.worktree_path, source: `${prefix}_worktree`, sessionId: session.id || null, label },
    { cwd: session.meta?.cwd, source: `${prefix}_session`, sessionId: session.id || null, label },
    { cwd: session.project_path, source: `${prefix}_project`, sessionId: session.id || null, label },
    { cwd: session.meta?.project_path, source: `${prefix}_project`, sessionId: session.id || null, label },
  ];
}

function firstExistingCandidate(candidates) {
  for (const candidate of candidates) {
    const cwd = firstExistingPath([candidate.cwd]);
    if (!cwd) continue;
    return { ...candidate, cwd };
  }
  return null;
}

function resolveWalleChatContext({ session, contextSession, requestedCwd } = {}) {
  const contextCandidate = contextSession && contextSession.id !== session?.id
    ? firstExistingCandidate(buildSessionPathCandidates(contextSession, 'context'))
    : null;
  const requestCandidate = requestedCwd
    ? firstExistingCandidate([{ cwd: requestedCwd, source: 'request', sessionId: null, label: '' }])
    : null;
  const sessionCandidate = firstExistingCandidate(buildSessionPathCandidates(session, 'walle'));

  if (sessionCandidate) {
    const ignoredContextCwd = contextCandidate && contextCandidate.cwd !== sessionCandidate.cwd
      ? contextCandidate.cwd
      : '';
    const ignoredRequestedCwd = requestCandidate && requestCandidate.cwd !== sessionCandidate.cwd
      ? requestCandidate.cwd
      : '';
    return {
      cwd: sessionCandidate.cwd,
      source: sessionCandidate.source,
      contextSessionId: contextCandidate?.sessionId || null,
      contextSessionLabel: contextCandidate?.label || '',
      contextCwd: contextCandidate?.cwd || '',
      ignoredContextCwd,
      ignoredRequestedCwd,
    };
  }

  const fallback = contextCandidate || requestCandidate;
  if (fallback) {
    return {
      cwd: fallback.cwd,
      source: fallback.source,
      contextSessionId: fallback.sessionId,
      contextSessionLabel: fallback.label,
      contextCwd: fallback.source.startsWith('context_') ? fallback.cwd : '',
      ignoredContextCwd: '',
      ignoredRequestedCwd: '',
    };
  }

  return {
    cwd: '',
    source: 'none',
    contextSessionId: null,
    contextSessionLabel: '',
    contextCwd: '',
    ignoredContextCwd: '',
    ignoredRequestedCwd: '',
  };
}

module.exports = {
  resolveWalleChatContext,
};
