const ranges = [
    { minRange: 1, maxRange: 79, tag: "T , Foil" },
    { minRange: 1, maxRange: 116, tag: "C , Foil" },
    { minRange: 1, maxRange: 116, tag: "C , Foil" },
    { minRange: 1, maxRange: 116, tag: "C , Foil" },
    { minRange: 1, maxRange: 116, tag: "C , Foil" },
    { minRange: 1, maxRange: 116, tag: "C , Foil" },
    { minRange: 1, maxRange: 79, tag: "U , Foil" },
    { minRange: 1, maxRange: 79, tag: "U , Foil" },
    { minRange: 1, maxRange: 20, tag: "MUL U Multi , Foil" },
    { minRange: 1, maxRange: 10, tag: "L , Foil" },
    { minRange: 1, maxRange: 100, tag: "Slot10" },
    { minRange: 1, maxRange: 60, tag: "R , Foil" },
    { minRange: 1, maxRange: 20, tag: "M , Foil" },
    { minRange: 1, maxRange: 100, tag: "Slot11" },
    { minRange: 1, maxRange: 38, tag: "Extended Art , Normal" },
    { minRange: 1, maxRange: 54, tag: "MOC Extended Art , Normal" },
    { minRange: 1, maxRange: 100, tag: "Slot12" },
    { minRange: 1, maxRange: 18, tag: "R Show , Normal" },
    { minRange: 1, maxRange: 10, tag: "M Show , Normal" },
    { minRange: 1, maxRange: 3, tag: "Borderless , Normal" },
    { minRange: 1, maxRange: 38, tag: "Extended Art , Normal" },
    { minRange: 1, maxRange: 100, tag: "Slot13" },
    { minRange: 1, maxRange: 20, tag: "MUL U Etched , Foil" },
    { minRange: 1, maxRange: 20, tag: "MUL U Halo , Foil" },
    { minRange: 1, maxRange: 20, tag: "MUL U Serial , Foil" },
    { minRange: 1, maxRange: 100, tag: "Slot14" },
    { minRange: 1, maxRange: 18, tag: "R Show , Foil" },
    { minRange: 1, maxRange: 10, tag: "M Show , Foil" },
    { minRange: 1, maxRange: 3, tag: "Borderless , Foil" },
    { minRange: 1, maxRange: 38, tag: "Extended Art , Foil" },
    { minRange: 1, maxRange: 5, tag: "Serial , Foil" },
    { minRange: 1, maxRange: 100, tag: "Slot15" },
    { minRange: 1, maxRange: 30, tag: "MUL R Multi , Foil" },
    { minRange: 1, maxRange: 30, tag: "MUL M Multi , Foil" },
    { minRange: 1, maxRange: 15, tag: "MUL M Etched , Foil" },
    { minRange: 1, maxRange: 14, tag: "MUL M Halo , Foil" },
    { minRange: 1, maxRange: 30, tag: "MUL R Halo , Foil" },
    { minRange: 1, maxRange: 30, tag: "MUL R Etched , Foil" },
    { minRange: 1, maxRange: 30, tag: "MUL R Serial , Foil" },
    { minRange: 1, maxRange: 14, tag: "MUL M Serial , Foil" },
    { minRange: 1, maxRange: 500, tag: "Userialodds" },
    { minRange: 1, maxRange: 2000, tag: "Serialodds" },
    { minRange: 1, maxRange: 667, tag: "Rmserialodds" },
];

function incrementNonce(nonce, offset) {
  let seconds = parseInt(nonce.slice(0, 2), 10);
  let minutes = parseInt(nonce.slice(2, 4), 10);
  let hours = parseInt(nonce.slice(4, 6), 10);
  let day = parseInt(nonce.slice(6, 8), 10);
  let month = parseInt(nonce.slice(8, 10), 10);
  let year = parseInt(nonce.slice(10, 14), 10);

  seconds += offset;
  while (seconds > 59) {
    seconds -= 60;
    minutes += 1;
    if (minutes > 59) {
      minutes = 0;
      hours += 1;
      if (hours > 23) {
        hours = 0;
        day += 1;
        const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (day > daysInMonth[month - 1]) {
          day = 1;
          month += 1;
          if (month > 12) {
            month = 1;
            year += 1;
          }
        }
      }
    }
  }

  return (
    seconds.toString().padStart(2, '0') +
    minutes.toString().padStart(2, '0') +
    hours.toString().padStart(2, '0') +
    day.toString().padStart(2, '0') +
    month.toString().padStart(2, '0') +
    year.toString().padStart(4, '0')
  );
}

async function generateHmacSha512(key, message) {
  const keyBuffer = new TextEncoder().encode(key);
  const msgBuffer = new TextEncoder().encode(message);
  const cryptoKey = await crypto.subtle.importKey(
    "raw",
    keyBuffer,
    { name: "HMAC", hash: "SHA-512" },
    false,
    ["sign"]
  );
  const signature = await crypto.subtle.sign("HMAC", cryptoKey, msgBuffer);
  return new Uint8Array(signature);
}

async function generateRandomNumbers(ranges, serverSeed, clientSeed, nonce) {
  const randomNumbers = [];
  const numbersPerDigest = 16;
  const digestsNeeded = Math.ceil(ranges.length / numbersPerDigest);

  for (let digestIndex = 0; digestIndex < digestsNeeded; digestIndex++) {
    const message = `${clientSeed}:${nonce}:${digestIndex}`;
    const digest = await generateHmacSha512(serverSeed, message);
    let offset = 0;

    for (let i = 0; i < numbersPerDigest && randomNumbers.length < ranges.length; i++) {
      const range = ranges[randomNumbers.length];
      const bytes = digest.slice(offset, offset + 4);
      const view = new DataView(bytes.buffer, bytes.byteOffset, 4);
      const num = view.getUint32(0, false); // Big-endian
      const rand = Math.floor((num / 0x100000000) * (range.maxRange - range.minRange + 1)) + range.minRange;
      randomNumbers.push(rand);
      offset += 4;
    }
  }

  return randomNumbers;
}

async function mapTaggedResults(randomNumbers, ranges, serverSeed, clientSeed, nonce) {
  const seenValues = {};
  const taggedResults = [];

  for (let index = 0; index < randomNumbers.length; index++) {
    if (!ranges[index]) {
      console.error(`No range found for index ${index}`);
      continue;
    }

    const { tag = "UNKNOWN", minRange, maxRange } = ranges[index];
    let finalNumber = randomNumbers[index];
    let nonceOffset = 0;

    if (!seenValues[tag]) {
      seenValues[tag] = new Set();
    }

    while (seenValues[tag].has(finalNumber.toString())) {
      nonceOffset++;
      const newNonce = incrementNonce(nonce, nonceOffset);
      const message = `${clientSeed}:${newNonce}`;
      const digest = await generateHmacSha512(serverSeed, message);
      const bytes = digest.slice(0, 4);
      const view = new DataView(bytes.buffer, bytes.byteOffset, 4);
      const newNum = view.getUint32(0, false); // Big-endian
      finalNumber = Math.floor((newNum / 0x100000000) * (maxRange - minRange + 1)) + minRange;
    }

    seenValues[tag].add(finalNumber.toString());
    taggedResults.push({ value: finalNumber.toString(), tag });
  }

  return taggedResults;
}

async function filterResults(taggedResults, ranges, serverSeed, clientSeed, nonce) {
    let filteredResults = [];
    const usedIndexes = new Set();

    const findAndConsume = (tag) => {
        const item = taggedResults.find((item, i) => item.tag === tag && !usedIndexes.has(i));
        if (item) usedIndexes.add(taggedResults.indexOf(item));
        return item;
    };

    const add = (item) => { if (item) filteredResults.push(item); };

    let tFrameFoil = taggedResults.filter((item, i) => item.tag === "T , Foil" && !usedIndexes.has(i));
    tFrameFoil.slice(0, 1).forEach(item => {
        usedIndexes.add(taggedResults.indexOf(item));
        filteredResults.push(item);
    });

    let cFoil = taggedResults.filter((item, i) => item.tag === "C , Foil" && !usedIndexes.has(i));
    cFoil.slice(0, 5).forEach(item => {
        usedIndexes.add(taggedResults.indexOf(item));
        filteredResults.push(item);
    });

    let uFoil = taggedResults.filter((item, i) => item.tag === "U , Foil" && !usedIndexes.has(i));
    uFoil.slice(0, 2).forEach(item => {
        usedIndexes.add(taggedResults.indexOf(item));
        filteredResults.push(item);
    });

    let lFoil = taggedResults.filter((item, i) => item.tag === "L , Foil" && !usedIndexes.has(i));
    lFoil.slice(0, 1).forEach(item => {
        usedIndexes.add(taggedResults.indexOf(item));
        filteredResults.push(item);
    });

    let usFoil = taggedResults.filter((item, i) => item.tag === "MUL U Multi , Foil" && !usedIndexes.has(i));
    usFoil.slice(0, 1).forEach(item => {
        usedIndexes.add(taggedResults.indexOf(item));
        filteredResults.push(item);
    });

    const slot10 = taggedResults.find(item => item.tag === "Slot10");
    let slot10Item = null;
    let slot10Tag = null;
    if (slot10) {
        const num = parseInt(slot10.value, 10);
        if (num <= 87) {
            slot10Tag = "R , Foil";
            slot10Item = findAndConsume("R , Foil");
        } else if (num <= 100) {
            slot10Tag = "M , Foil";
            slot10Item = findAndConsume("M , Foil");
        }
        add(slot10Item);
    }

    const slot11 = taggedResults.find(item => item.tag === "Slot11");
    let slot11Item = null;
    let slot11Tag = null;
    if (slot11) {
        const num = parseInt(slot11.value, 10);
        if (num <= 40) {
            slot11Tag = "Extended Art , Normal";
            slot11Item = findAndConsume("Extended Art , Normal");
        } else if (num <= 100) {
            slot11Tag = "MOC Extended Art , Normal";
            slot11Item = findAndConsume("MOC Extended Art , Normal");
        }
        add(slot11Item);
    }

    const slot12 = taggedResults.find(item => item.tag === "Slot12");
    let slot12Item = null;
    let slot12Tag = null;
    if (slot12) {
        const num = parseInt(slot12.value, 10);
        if (num <= 30) {
            slot12Tag = "R Show , Normal";
            slot12Item = findAndConsume("R Show , Normal");
        } else if (num <= 46) {
            slot12Tag = "M Show , Normal";
            slot12Item = findAndConsume("M Show , Normal");
        } else if (num <= 48) {
            slot12Tag = "Borderless , Normal";
            slot12Item = findAndConsume("Borderless , Normal");
        } else if (num <= 100) {
            slot12Tag = "Extended Art , Normal";
            slot12Item = findAndConsume("Extended Art , Normal");
        }
        add(slot12Item);
    }

    const serialU = taggedResults.find(item => item.tag === "Userialodds");
    let serialUItem = null;
    let serialUTag = null;
    if (serialU && serialU.value === "500") {
        serialUTag = "MUL U Serial , Foil";
        serialUItem = findAndConsume("MUL U Serial , Foil");
        add(serialUItem);
    } else if (serialU) {
        const slot13 = taggedResults.find(item => item.tag === "Slot13");
        if (slot13) {
            const num = parseInt(slot13.value, 10);
            if (num <= 75) {
                serialUTag = "MUL U Etched , Foil";
                serialUItem = findAndConsume("MUL U Etched , Foil");
            } else if (num <= 100) {
                serialUTag = "MUL U Halo , Foil";
                serialUItem = findAndConsume("MUL U Halo , Foil");
            }
            add(serialUItem);
        }
    }

    const serialS = taggedResults.find(item => item.tag === "Serialodds");
    let serialSItem = null;
    let serialSTag = null;
    if (serialS && serialS.value === "2000") {
        serialSTag = "Serial , Foil";
        serialSItem = findAndConsume("Serial , Foil");
        add(serialSItem);
    } else if (serialS) {
        const slot14 = taggedResults.find(item => item.tag === "Slot14");
        if (slot14) {
            const num = parseInt(slot14.value, 10);
            if (num <= 30) {
                serialSTag = "R Show , Foil";
                serialSItem = findAndConsume("R Show , Foil");
            } else if (num <= 46) {
                serialSTag = "M Show , Foil";
                serialSItem = findAndConsume("M Show , Foil");
            } else if (num <= 48) {
                serialSTag = "Borderless , Foil";
                serialSItem = findAndConsume("Borderless , Foil");
            } else if (num <= 100) {
                serialSTag = "Extended Art , Foil";
                serialSItem = findAndConsume("Extended Art , Foil");
            }
            add(serialSItem);
        }
    }

    const serialRm = taggedResults.find(item => item.tag === "Rmserialodds");
    let serialRmItem = null;
    let serialRmTag = null;
    if (serialRm) {
        if (serialRm.value === "665" || serialRm.value === "666") {
            serialRmTag = "MUL R Serial , Foil";
            serialRmItem = findAndConsume("MUL R Serial , Foil");
        } else if (serialRm.value === "667") {
            serialRmTag = "MUL M Serial , Foil";
            serialRmItem = findAndConsume("MUL M Serial , Foil");
        } else {
            const slot15 = taggedResults.find(item => item.tag === "Slot15");
            if (slot15) {
                const num = parseInt(slot15.value, 10);
                if (num <= 50) {
                    serialRmTag = "MUL R Multi , Foil";
                    serialRmItem = findAndConsume("MUL R Multi , Foil");
                } else if (num <= 75) {
                    serialRmTag = "MUL M Multi , Foil";
                    serialRmItem = findAndConsume("MUL M Multi , Foil");
                } else if (num <= 80) {
                    serialRmTag = "MUL M Etched , Foil";
                    serialRmItem = findAndConsume("MUL M Etched , Foil");
                } else if (num <= 83) {
                    serialRmTag = "MUL M Halo , Foil";
                    serialRmItem = findAndConsume("MUL M Halo , Foil");
                } else if (num <= 91) {
                    serialRmTag = "MUL R Halo , Foil";
                    serialRmItem = findAndConsume("MUL R Halo , Foil");
                } else if (num <= 100) {
                    serialRmTag = "MUL R Etched , Foil";
                    serialRmItem = findAndConsume("MUL R Etched , Foil");
                }
                add(serialRmItem);
            }
        }
        add(serialRmItem);
    }

    return filteredResults;
}

async function setData(serverSeed, clientSeed, nonce) {
  const randomNumbers = await generateRandomNumbers(ranges, serverSeed, clientSeed, nonce);
  const taggedResults = await mapTaggedResults(randomNumbers, ranges, serverSeed, clientSeed, nonce);
  const filteredResults = await filterResults(taggedResults, ranges, serverSeed, clientSeed, nonce);

  return {
    success: true,
    result: filteredResults,
    nonce,
    serverSeed,
    clientSeed
  };
}
export { setData, ranges};
