import { syntaxTree } from '@codemirror/language';
import { EditorState } from '@codemirror/state';

export function computeJsonPath(state: EditorState, pos: number): string {
  const tree = syntaxTree(state);
  const node = tree.resolveInner(pos, 1);

  const parts: Array<string | number> = [];
  const valueNodes = new Set([
    'Object',
    'Array',
    'String',
    'Number',
    'True',
    'False',
    'Null',
  ]);
  let prev = node;
  let cur = node.parent;

  while (cur) {
    if (cur.name === 'Property') {
      const nameNode = cur.getChild('PropertyName');
      if (nameNode) {
        const raw = state.sliceDoc(nameNode.from, nameNode.to);
        parts.unshift(raw.slice(1, -1));
      }
    } else if (cur.name === 'Array') {
      let index = 0;
      let child = cur.firstChild;
      while (child) {
        if (child.from === prev.from && child.to === prev.to) break;
        if (valueNodes.has(child.name)) index++;
        child = child.nextSibling;
      }
      parts.unshift(index);
    }
    prev = cur;
    cur = cur.parent;
  }

  return parts.reduce<string>((path, part) => {
    return typeof part === 'number' ? `${path}[${part}]` : `${path}.${part}`;
  }, '$');
}
