import { projectFilePath } from '@learnitive/project-storage';
import type { ProjectGitFileChange } from './types';

/**
 * Convert isomorphic-git's statusMatrix tuple values into the two user-facing
 * Learnitive change buckets. Stage=2 represents an indexed file matching workdir;
 * stage=3 represents an indexed file that has been modified again afterwards.
 */
export function mapProjectGitStatus(
  path: string,
  head: number,
  workdir: number,
  stage: number,
): { staged?: ProjectGitFileChange; unstaged?: ProjectGitFileChange } {
  const projectPath = projectFilePath(path);
  let staged: ProjectGitFileChange | undefined;
  let unstaged: ProjectGitFileChange | undefined;

  if (head === 0 && (stage === 2 || stage === 3)) {
    staged = { path: projectPath, status: 'added', staged: true };
  } else if (head === 1 && (stage === 2 || stage === 3)) {
    staged = { path: projectPath, status: 'modified', staged: true };
  } else if (head === 1 && stage === 0) {
    staged = { path: projectPath, status: 'deleted', staged: true };
  }

  if (head === 0 && workdir === 2 && stage === 0) {
    unstaged = { path: projectPath, status: 'untracked', staged: false };
  } else if (workdir === 2 && stage === 1) {
    unstaged = { path: projectPath, status: 'modified', staged: false };
  } else if (workdir === 0 && stage === 1 && head === 1) {
    unstaged = { path: projectPath, status: 'deleted', staged: false };
  } else if (workdir === 2 && stage === 3) {
    unstaged = { path: projectPath, status: 'modified', staged: false };
  }

  return { staged, unstaged };
}
