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

import {
  assertArgs,
  lastPathSegment,
  stripSuffix,
} from "../_common/basename.ts";
import { stripTrailingSeparators } from "../_common/strip_trailing_separators.ts";
import { isPosixPathSeparator } from "./_util.ts";

/**
 * Return the last portion of a `path`.
 * Trailing directory separators are ignored, and optional suffix is removed.
 *
 * @example
 * ```ts
 * import { basename } from "@std/path/basename";
 *
 * console.log(basename("/home/user/Documents/")); // "Documents"
 * console.log(basename("/home/user/Documents/image.png")); // "image.png"
 * console.log(basename("/home/user/Documents/image.png", ".png")); // "image"
 * ```
 *
 * @param path - path to extract the name from.
 * @param [suffix] - suffix to remove from extracted name.
 */
export function basename(path: string, suffix = ""): string {
  assertArgs(path, suffix);

  const lastSegment = lastPathSegment(path, isPosixPathSeparator);
  const strippedSegment = stripTrailingSeparators(
    lastSegment,
    isPosixPathSeparator,
  );
  return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;
}

// denoCacheMetadata={"headers":{"server":"cloudflare","date":"Tue, 28 Jul 2026 12:31:15 GMT","accept-ranges":"bytes","content-type":"text/typescript","x-jsr-backend":"modules","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","age":"612446","cf-cache-status":"HIT","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';","cf-ray":"a223e6583bd87db6-LAX","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","access-control-expose-headers":"*","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","access-control-allow-origin":"*","set-cookie":"__cf_bm=IVsrie2PkXjUDzck86IIaDBNIWYwF5hlU_i5lOgjJ8U-1785241875.2440972-1.0.1.1-AgBDYfd4xcn.TElSOGz6nJPeEquprXMVZaLbODtKVt43pc2BwjhGqbrUKcS16JrZ2PXba6acQMQZB0T1KoYCNH5Z7oYhK0BIC2N0qZU1l_hTyICbq6gWebzwBwPvfaUc; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","vary":"Origin","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=Io1BpujmM2X3UFnvIf9RL1GHnRV9m37Gv%2BHcYo0Tzh84gPRH6xDdoOqDVEL6B8QzaD10bxU72oX70OhbXM%2B8wkhuSeigRyUYJRmJ3pf4Z3KpgD3rd9oT3DA%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","etag":"\"56d711fa87638a8023c1a3eb6e8b4da9\"","content-length":"1212"},"url":"https://jsr.io/@std/path/0.224.0/posix/basename.ts","time":1785241875}