// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { CHAR_COLON, CHAR_DOT } from "../_common/constants.ts";
import { assertPath } from "../_common/assert_path.ts";
import { isPathSeparator, isWindowsDeviceRoot } from "./_util.ts";

/**
 * Return the extension of the `path` with leading period.
 *
 * @example Usage
 * ```ts
 * import { extname } from "@std/path/windows/extname";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const ext = extname("file.ts");
 * assertEquals(ext, ".ts");
 * ```
 *
 * @param path The path to get the extension from.
 * @returns The extension of the `path`.
 */
export function extname(path: string): string {
  assertPath(path);

  let start = 0;
  let startDot = -1;
  let startPart = 0;
  let end = -1;
  let matchedSlash = true;
  // Track the state of characters (if any) we see before our first dot and
  // after any path separator we find
  let preDotState = 0;

  // Check for a drive letter prefix so as not to mistake the following
  // path separator as an extra separator at the end of the path that can be
  // disregarded

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2;
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i);
    if (isPathSeparator(code)) {
      // If we reached a path separator that was not part of a set of path
      // separators at the end of the string, stop now
      if (!matchedSlash) {
        startPart = i + 1;
        break;
      }
      continue;
    }
    if (end === -1) {
      // We saw the first non-path separator, mark this as the end of our
      // extension
      matchedSlash = false;
      end = i + 1;
    }
    if (code === CHAR_DOT) {
      // If this is our first dot, mark it as the start of our extension
      if (startDot === -1) startDot = i;
      else if (preDotState !== 1) preDotState = 1;
    } else if (startDot !== -1) {
      // We saw a non-dot and non-path separator before our dot, so we should
      // have a good chance at having a non-empty extension
      preDotState = -1;
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    // We saw a non-dot character immediately before the dot
    preDotState === 0 ||
    // The (right-most) trimmed path component is exactly '..'
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return "";
  }
  return path.slice(startDot, end);
}

// denoCacheMetadata={"headers":{"x-jsr-backend":"modules","x-content-type-options":"nosniff","date":"Tue, 28 Jul 2026 12:31:15 GMT","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","access-control-allow-origin":"*","cf-ray":"a223e658cdb47db6-LAX","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","vary":"Origin","cross-origin-resource-policy":"cross-origin","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=m2bv7WbK%2FLdSng9F2jMB%2F%2BQyL5LUxAdIEFFKf8Df9aSA08PdN3Bz2sbCEnW9L2uQV27SnD8%2B%2BB6OXZunUa0Sa71uhrKZXm1Aoyg%2FzjzllLUOZLzC3HTtb7k%3D\"}]}","access-control-expose-headers":"*","alt-svc":"h3=\":443\"; ma=86400","content-length":"2572","content-type":"text/typescript","cache-control":"public, max-age=31536000, immutable","set-cookie":"__cf_bm=vM2evi05QoeC1ZUA6JilYvVTqMsE9Sdj1TQukOVFq3s-1785241875.3434181-1.0.1.1-gsPsgqncf2m4ror.KIXl6UOAPyQzG9JvhZzapBg2NpMqbfFTWnkpC2GLO3HwaBbQhKSWVBoyKijJt8cc.7Gz7Uw6fa1TPVmIRAsRFFh6Ofm16aNlDoxki7PppqMHIlEM; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","server":"cloudflare","etag":"\"3dc41e477f9de52d385dcfa99848bfcc\"","x-robots-tag":"noindex"},"url":"https://jsr.io/@std/path/1.0.0-rc.2/windows/extname.ts","time":1785241875}