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

import { CHAR_DOT } from "../_common/constants.ts";
import { assertPath } from "../_common/assert_path.ts";
import { isPosixPathSeparator } from "./_util.ts";

/**
 * Return the extension of the `path` with leading period.
 *
 * @example Usage
 * ```ts
 * import { extname } from "@std/path/posix/extname";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(extname("/home/user/Documents/file.ts"), ".ts");
 * assertEquals(extname("/home/user/Documents/"), "");
 * assertEquals(extname("/home/user/Documents/image.png"), ".png");
 * ```
 *
 * @param path The path to get the extension from.
 * @returns The extension (ex. for `file.ts` returns `.ts`).
 */
export function extname(path: string): string {
  assertPath(path);

  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;
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i);
    if (isPosixPathSeparator(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":{"age":"126790","cf-cache-status":"HIT","cf-ray":"a223e658cdb17db6-LAX","etag":"\"ceb85fd30e884f78ae9182c4e9c72dc9\"","date":"Tue, 28 Jul 2026 12:31:15 GMT","vary":"Origin","x-content-type-options":"nosniff","access-control-expose-headers":"*","x-robots-tag":"noindex","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=tlAT9gMIZfDGF5dV3UYCxc25c0AVHAJwod027HLMSs7scgdDgIkDjY8hdW17DPAsz29rg7qGA7URjj%2Bacp1C9oJF%2Follm%2BTgPwePs7%2BHm0qjMqAeZ3EPXlQ%3D\"}]}","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","set-cookie":"__cf_bm=rUUUaM7qp0iG7DIEGCDEZyd7o5oFEP.EQT7vgmw5LDk-1785241875.3426113-1.0.1.1-xiPUi1UgwoMmbU3_hfLlVeU.i8iT9Ivoo_0c5m7lO9dClAUw33BriHOcoMU__FNlKaKGN54mUmUaOlkXtAbrGmo61KOuNgPSGwFfgYkzwFXcyoROG6fWDKk94uSlzKFa; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","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';","access-control-allow-origin":"*","content-length":"2348","content-type":"text/typescript","accept-ranges":"bytes","server":"cloudflare","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","alt-svc":"h3=\":443\"; ma=86400","cache-control":"public, max-age=31536000, immutable"},"url":"https://jsr.io/@std/path/1.0.0-rc.2/posix/extname.ts","time":1785241875}