import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { pathToFileURL } from "node:url";

// Small protobuf wire reader for inspecting existing ONNX metadata. This does
// not execute, modify or claim to fully validate an ONNX model. No dependencies.
function varint(bytes, start) {
  let value = 0n, shift = 0n, offset = start;
  while (offset < bytes.length && shift < 70n) {
    const byte = bytes[offset++];
    value |= BigInt(byte & 127) << shift;
    if (!(byte & 128)) return { value, offset };
    shift += 7n;
  }
  throw new Error("Malformed protobuf varint");
}

function fields(bytes) {
  const result = new Map();
  let offset = 0;
  while (offset < bytes.length) {
    let entry = varint(bytes, offset);
    offset = entry.offset;
    const tag = Number(entry.value), field = tag >>> 3, wire = tag & 7;
    let value;
    if (wire === 0) {
      entry = varint(bytes, offset);
      value = entry.value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(entry.value) : entry.value.toString();
      offset = entry.offset;
    } else if (wire === 2) {
      entry = varint(bytes, offset);
      const length = Number(entry.value);
      offset = entry.offset;
      if (!Number.isSafeInteger(length) || offset + length > bytes.length) throw new Error("Truncated protobuf field");
      value = bytes.subarray(offset, offset + length);
      offset += length;
    } else if (wire === 1 || wire === 5) {
      const length = wire === 1 ? 8 : 4;
      if (offset + length > bytes.length) throw new Error("Truncated protobuf field");
      value = bytes.subarray(offset, offset + length);
      offset += length;
    } else {
      throw new Error(`Unsupported protobuf wire type ${wire}`);
    }
    if (!result.has(field)) result.set(field, []);
    result.get(field).push(value);
  }
  return result;
}

const first = (message, field) => message.get(field)?.[0];
const string = (value) => value?.toString("utf8");
function valueInfo(bytes) {
  const value = fields(bytes);
  const tensor = fields(first(fields(first(value, 2)), 1));
  const shape = fields(first(tensor, 2));
  return {
    name: string(first(value, 1)),
    elementType: first(tensor, 1),
    dims: (shape.get(1) || []).map((dimension) => {
      const dim = fields(dimension);
      return dim.has(1) ? first(dim, 1) : string(first(dim, 2));
    }),
  };
}

function nodeInfo(bytes, index) {
  const node = fields(bytes);
  const attributes = {};
  for (const bytes of node.get(5) || []) {
    const attr = fields(bytes), name = string(first(attr, 1));
    if (attr.has(8)) {
      const values = [];
      for (const item of attr.get(8)) {
        if (!Buffer.isBuffer(item)) { values.push(item); continue; }
        let offset = 0;
        while (offset < item.length) {
          const entry = varint(item, offset);
          values.push(Number(entry.value));
          offset = entry.offset;
        }
      }
      attributes[name] = values;
    } else if (attr.has(4)) attributes[name] = string(first(attr, 4));
    else if (attr.has(3)) attributes[name] = first(attr, 3);
  }
  return { index, opType: string(first(node, 4)), inputs: (node.get(1) || []).map(string), outputs: (node.get(2) || []).map(string), attributes, rawNodeProtobufHex: bytes.toString("hex") };
}

export function inspectOnnxLayout(path) {
  const bytes = readFileSync(path);
  const graph = fields(first(fields(bytes), 7));
  const nodes = graph.get(1) || [];
  return {
    modelBytes: bytes.length,
    modelSha256: createHash("sha256").update(bytes).digest("hex"),
    inputs: (graph.get(11) || []).map(valueInfo),
    outputs: (graph.get(12) || []).map(valueInfo),
    nodeCount: nodes.length,
    boundaryNodes: [...new Set([0, 1, nodes.length - 2, nodes.length - 1])].map((index) => nodeInfo(nodes[index], index)),
  };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  if (!process.argv[2]) throw new Error("Usage: node inspect-model-layout.mjs /path/to/animeganv3_hayao_36.onnx");
  console.log(JSON.stringify(inspectOnnxLayout(process.argv[2]), null, 2));
}
