// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import type { StyleVariant, Type } from "../_type.ts";
import { isNegativeZero } from "../_utils.ts";

const YAML_FLOAT_PATTERN = new RegExp(
  // 2.5e4, 2.5 and integers
  "^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" +
    // .2e4, .2
    // special case, seems not from spec
    "|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" +
    // .inf
    "|[-+]?\\.(?:inf|Inf|INF)" +
    // .nan
    "|\\.(?:nan|NaN|NAN))$",
);

function resolveYamlFloat(data: string): boolean {
  if (
    !YAML_FLOAT_PATTERN.test(data) ||
    // Quick hack to not allow integers end with `_`
    // Probably should update regexp & check speed
    data[data.length - 1] === "_"
  ) {
    return false;
  }

  return true;
}

function constructYamlFloat(data: string): number {
  let value = data.replace(/_/g, "").toLowerCase();
  const sign = value[0] === "-" ? -1 : 1;

  if (value[0] && "+-".includes(value[0])) {
    value = value.slice(1);
  }

  if (value === ".inf") {
    return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
  }
  if (value === ".nan") {
    return NaN;
  }
  return sign * parseFloat(value);
}

const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;

function representYamlFloat(
  // deno-lint-ignore ban-types
  object: number | Number,
  style?: StyleVariant,
): string {
  const value = object instanceof Number ? object.valueOf() : object;
  if (isNaN(value)) {
    switch (style) {
      case "lowercase":
        return ".nan";
      case "uppercase":
        return ".NAN";
      case "camelcase":
        return ".NaN";
    }
  } else if (Number.POSITIVE_INFINITY === value) {
    switch (style) {
      case "lowercase":
        return ".inf";
      case "uppercase":
        return ".INF";
      case "camelcase":
        return ".Inf";
    }
  } else if (Number.NEGATIVE_INFINITY === value) {
    switch (style) {
      case "lowercase":
        return "-.inf";
      case "uppercase":
        return "-.INF";
      case "camelcase":
        return "-.Inf";
    }
  } else if (isNegativeZero(value)) {
    return "-0.0";
  }

  const res = value.toString(10);

  // JS stringifier can build scientific format without dots: 5e-100,
  // while YAML requires dot: 5.e-100. Fix it with simple hack

  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}

function isFloat(object: unknown): object is number {
  if (object instanceof Number) object = object.valueOf();
  return typeof object === "number" &&
    (object % 1 !== 0 || isNegativeZero(object));
}

export const float: Type<"scalar", number> = {
  tag: "tag:yaml.org,2002:float",
  construct: constructYamlFloat,
  defaultStyle: "lowercase",
  kind: "scalar",
  predicate: isFloat,
  represent: representYamlFloat,
  resolve: resolveYamlFloat,
};

// denoCacheMetadata={"headers":{"x-content-type-options":"nosniff","content-length":"3027","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","server":"cloudflare","content-type":"text/typescript","access-control-allow-origin":"*","etag":"\"7ffdaba76fc16988e750533fb1c1e45b\"","cf-ray":"a223e6590e3c7db6-LAX","vary":"Origin","access-control-expose-headers":"*","set-cookie":"__cf_bm=h5CECbjMg0NcNKwupj72mQgUp64hN6vs0uhLibe8DIw-1785241875.369191-1.0.1.1-HADqlUAcbkM8C4PMZ5jl8L2IcqFLANzaJFnp0o2mpNkbpDN2vN0rA8IJHXjNpGSAV9FuZ9a99wdlTQZpEtCvMjMVMqwqhjmK5QPSl01Lqik0trYWV1CauvIROrruLxkg; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=DFBhdYEhau7zRIEcwCvudC%2F23j6pYZ8XoSW%2FuydYZIKDcV2%2FFcC3TJix%2Fi7JQjAYIj%2FH9FKQOha9Ihrstk%2Fp6ioJEKP1s1zfwgiYSK0gmuSxmZFDnNBGTdA%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","age":"471577","accept-ranges":"bytes","cf-cache-status":"HIT","date":"Tue, 28 Jul 2026 12:31:15 GMT","cache-control":"public, max-age=31536000, immutable","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}","x-jsr-backend":"modules"},"url":"https://jsr.io/@std/yaml/1.0.5/_type/float.ts","time":1785241875}