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

import { normalizeString } from "../_common/normalize_string.ts";
import { assertPath } from "../_common/assert_path.ts";
import { isPosixPathSeparator } from "./_util.ts";

/**
 * Resolves path segments into a `path`.
 *
 * @example Usage
 * ```ts
 * import { resolve } from "@std/path/posix/resolve";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const path = resolve("/foo", "bar", "baz/asdf", "quux", "..");
 * assertEquals(path, "/foo/bar/baz/asdf");
 * ```
 *
 * @param pathSegments The path segments to resolve.
 * @returns The resolved path.
 */
export function resolve(...pathSegments: string[]): string {
  let resolvedPath = "";
  let resolvedAbsolute = false;

  for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    let path: string;

    if (i >= 0) path = pathSegments[i]!;
    else {
      // deno-lint-ignore no-explicit-any
      const { Deno } = globalThis as any;
      if (typeof Deno?.cwd !== "function") {
        throw new TypeError("Resolved a relative path without a CWD.");
      }
      path = Deno.cwd();
    }

    assertPath(path);

    // Skip empty entries
    if (path.length === 0) {
      continue;
    }

    resolvedPath = `${path}/${resolvedPath}`;
    resolvedAbsolute = isPosixPathSeparator(path.charCodeAt(0));
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when Deno.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeString(
    resolvedPath,
    !resolvedAbsolute,
    "/",
    isPosixPathSeparator,
  );

  if (resolvedAbsolute) {
    if (resolvedPath.length > 0) return `/${resolvedPath}`;
    else return "/";
  } else if (resolvedPath.length > 0) return resolvedPath;
  else return ".";
}

// denoCacheMetadata={"headers":{"cf-ray":"a223e658edef7db6-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';","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","accept-ranges":"bytes","server":"cloudflare","vary":"Origin","cache-control":"public, max-age=31536000, immutable","alt-svc":"h3=\":443\"; ma=86400","set-cookie":"__cf_bm=Xya0H9DQi0pfO9ipCRHp5kalYDmDVslLfS0jD7dsTK4-1785241875.3535352-1.0.1.1-aCeRzOkKslfuGW9iCq2MV3qym5Wfk1dm2siv3zOu6oOSYJu.zyoniiAVV4RJRioI8C1y8suspH9nF.n6XEo.pg4fKu06C5cQ.fLw.N6oy7nArfr5aTr4ycxEKy8s.Ab8; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","x-jsr-backend":"modules","age":"197965","x-content-type-options":"nosniff","etag":"\"6cf039f0c27b9f60a520c95cc5e69c46\"","content-type":"text/typescript","access-control-expose-headers":"*","x-robots-tag":"noindex","cross-origin-resource-policy":"cross-origin","content-length":"1897","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-cache-status":"HIT","access-control-allow-origin":"*","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=4lAyde8o2JMK1ZsOgCm0FjSsCHtNiWivgHiSR5mwWLiPx%2FDWVBFpL0kfEFqbXnFDZ2fyWWYS6PcI0k13L%2BrbEDG3G2XrUg09pltxaGnYBdC10Wl%2BnXNbIhg%3D\"}]}"},"url":"https://jsr.io/@std/path/1.0.0-rc.2/posix/resolve.ts","time":1785241875}