/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {strict as assert} from 'node:assert';
import {EventEmitter} from 'node:events';
import * as path from 'node:path';
import anymatch from 'anymatch';
import watchman from 'fb-watchman';
import fs from 'graceful-fs';
import * as common from './common';

const CHANGE_EVENT = common.CHANGE_EVENT;
const DELETE_EVENT = common.DELETE_EVENT;
const ADD_EVENT = common.ADD_EVENT;
const ALL_EVENT = common.ALL_EVENT;
const SUB_NAME = 'jest-haste-map';

// Dedupe repeated "Recrawled this watch N times" warnings from watchman.
const RECRAWL_WARNINGS = [];
const RECRAWL_REGEXP =
  /Recrawled this watch (\d+) times, most recently because:\n([^:]+)/;

function isRecrawlWarningDupe(warningMessage) {
  if (typeof warningMessage !== 'string') {
    return false;
  }
  const match = warningMessage.match(RECRAWL_REGEXP);
  if (!match) {
    return false;
  }
  const count = Number(match[1]);
  const root = match[2];
  const existing = RECRAWL_WARNINGS.find(w => w.root === root);
  if (existing) {
    if (existing.count >= count) {
      return true;
    }
    existing.count = count;
    return false;
  }
  RECRAWL_WARNINGS.push({count, root});
  return false;
}

/**
 * Watches `dir`.
 *
 * @class WatchmanWatcher
 * @param String dir
 * @param {Object} opts
 * @public
 */

export default function WatchmanWatcher(dir, opts) {
  this.globs = opts.glob;
  this.dot = opts.dot;
  this.hasIgnore = Boolean(opts.ignored);
  this.doIgnore = opts.ignored ? anymatch(opts.ignored) : () => false;
  this.root = path.resolve(dir);
  this.init();
}

Object.setPrototypeOf(WatchmanWatcher.prototype, EventEmitter.prototype);

/**
 * Run the watchman `watch` command on the root and subscribe to changes.
 *
 * @private
 */

WatchmanWatcher.prototype.init = function () {
  if (this.client) {
    this.client.removeAllListeners();
  }

  const self = this;
  this.client = new watchman.Client();
  this.client.on('error', error => {
    self.emit('error', error);
  });
  this.client.on('subscription', this.handleChangeEvent.bind(this));
  this.client.on('end', () => {
    console.warn(
      '[jest-haste-map] Warning: Lost connection to watchman, reconnecting..',
    );
    self.init();
  });

  this.watchProjectInfo = null;

  function getWatchRoot() {
    return self.watchProjectInfo ? self.watchProjectInfo.root : self.root;
  }

  function onCapability(error, resp) {
    if (handleError(self, error)) {
      // The Watchman watcher is unusable on this system, we cannot continue
      return;
    }

    handleWarning(resp);

    self.capabilities = resp.capabilities;

    if (self.capabilities.relative_root) {
      self.client.command(['watch-project', getWatchRoot()], onWatchProject);
    } else {
      self.client.command(['watch', getWatchRoot()], onWatch);
    }
  }

  function onWatchProject(error, resp) {
    if (handleError(self, error)) {
      return;
    }

    handleWarning(resp);

    self.watchProjectInfo = {
      relativePath: resp.relative_path ?? '',
      root: resp.watch,
    };

    self.client.command(['clock', getWatchRoot()], onClock);
  }

  function onWatch(error, resp) {
    if (handleError(self, error)) {
      return;
    }

    handleWarning(resp);

    self.client.command(['clock', getWatchRoot()], onClock);
  }

  function onClock(error, resp) {
    if (handleError(self, error)) {
      return;
    }

    handleWarning(resp);

    const options = {
      fields: ['name', 'exists', 'new'],
      since: resp.clock,
    };

    // If the server has the wildmatch capability available it supports
    // the recursive **/*.foo style match and we can offload our globs
    // to the watchman server.  This saves both on data size to be
    // communicated back to us and compute for evaluating the globs
    // in our node process.
    if (self.capabilities.wildmatch) {
      if (self.globs.length === 0) {
        if (!self.dot) {
          // Make sure we honor the dot option if even we're not using globs.
          options.expression = [
            'match',
            '**',
            'wholename',
            {
              includedotfiles: false,
            },
          ];
        }
      } else {
        options.expression = ['anyof'];
        for (const glob of self.globs) {
          options.expression.push([
            'match',
            glob,
            'wholename',
            {
              includedotfiles: self.dot,
            },
          ]);
        }
      }
    }

    if (self.capabilities.relative_root) {
      options.relative_root = self.watchProjectInfo.relativePath;
    }

    self.client.command(
      ['subscribe', getWatchRoot(), SUB_NAME, options],
      onSubscribe,
    );
  }

  function onSubscribe(error, resp) {
    if (handleError(self, error)) {
      return;
    }

    handleWarning(resp);

    self.emit('ready');
  }

  self.client.capabilityCheck(
    {
      optional: ['wildmatch', 'relative_root'],
    },
    onCapability,
  );
};

/**
 * Handles a change event coming from the subscription.
 *
 * @param {Object} resp
 * @private
 */

WatchmanWatcher.prototype.handleChangeEvent = function (resp) {
  assert.equal(resp.subscription, SUB_NAME, 'Invalid subscription event.');
  if (resp.is_fresh_instance) {
    this.emit('fresh_instance');
  }
  if (Array.isArray(resp.files)) {
    for (const file of resp.files) this.handleFileChange(file);
  }
};

/**
 * Handles a single change event record.
 *
 * @param {Object} changeDescriptor
 * @private
 */

WatchmanWatcher.prototype.handleFileChange = function (changeDescriptor) {
  const self = this;
  let absPath;
  let relativePath;

  if (this.capabilities.relative_root) {
    relativePath = changeDescriptor.name;
    absPath = path.join(
      this.watchProjectInfo.root,
      this.watchProjectInfo.relativePath,
      relativePath,
    );
  } else {
    absPath = path.join(this.root, changeDescriptor.name);
    relativePath = changeDescriptor.name;
  }

  if (
    !(self.capabilities.wildmatch && !this.hasIgnore) &&
    !common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)
  ) {
    return;
  }

  if (changeDescriptor.exists) {
    fs.lstat(absPath, (error, stat) => {
      // Files can disappear or temporarily become unreadable between the
      // Watchman event and the lstat call, so ignore that stale event.
      if (error && common.isIgnorableFileError(error)) {
        return;
      }

      if (handleError(self, error)) {
        return;
      }

      const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT;

      // Change event on dirs are mostly useless.
      if (!(eventType === CHANGE_EVENT && stat.isDirectory())) {
        self.emitEvent(eventType, relativePath, self.root, stat);
      }
    });
  } else {
    self.emitEvent(DELETE_EVENT, relativePath, self.root);
  }
};

/**
 * Dispatches the event.
 *
 * @param {string} eventType
 * @param {string} filepath
 * @param {string} root
 * @param {fs.Stat} stat
 * @private
 */

WatchmanWatcher.prototype.emitEvent = function (
  eventType,
  filepath,
  root,
  stat,
) {
  this.emit(eventType, filepath, root, stat);
  this.emit(ALL_EVENT, eventType, filepath, root, stat);
};

/**
 * Closes the watcher.
 *
 */

WatchmanWatcher.prototype.close = function () {
  this.client.removeAllListeners();
  this.client.end();
  return Promise.resolve();
};

/**
 * Handles an error and returns true if exists.
 *
 * @param {WatchmanWatcher} self
 * @param {Error} error
 * @private
 */

function handleError(self, error) {
  if (error == null) {
    return false;
  } else {
    self.emit('error', error);
    return true;
  }
}

/**
 * Handles a warning in the watchman resp object.
 *
 * @param {object} resp
 * @private
 */

function handleWarning(resp) {
  if ('warning' in resp) {
    if (isRecrawlWarningDupe(resp.warning)) {
      return true;
    }
    console.warn(resp.warning);
    return true;
  } else {
    return false;
  }
}
