import type { Normalization, RelationGraph } from "../../../universal/src/graph.js";
import type { ExtractedRepresentation } from "./types.js";

export const REMAINING_PERCENTAGE_NORMALIZATION: Normalization = {
  name: "remaining-percentage",
  apply(value: unknown): unknown {
    if (typeof value === "string") {
      const match = /(\d+(?:\.\d+)?)\s*%\s*left/i.exec(value);
      if (match?.[1] !== undefined) {
        return Number(match[1]);
      }
      const generic = /(\d+(?:\.\d+)?)\s*%/.exec(value);
      if (generic?.[1] !== undefined) {
        return Number(generic[1]);
      }
    }
    if (typeof value === "number" && Number.isFinite(value)) {
      return value;
    }
    throw new Error("cannot normalize to remaining percentage");
  },
};

function nodeForRepresentation(representation: ExtractedRepresentation) {
  return {
    id: representation.id,
    representation: {
      source: representation.source,
      kind: representation.kind,
      value: representation.value,
      provenance: representation.provenance,
    },
  };
}

export function buildQuotaRelationGraph(
  representations: ExtractedRepresentation[],
): RelationGraph {
  const nodes = Object.fromEntries(
    representations.map((representation) => [
      representation.id,
      nodeForRepresentation(representation),
    ]),
  );

  const relationNodes = representations.map((representation) => representation.id);

  return {
    nodes,
    relations: {
      "quota-remaining": {
        kind: "same-semantic",
        nodes: relationNodes,
        declaredBy: "UNI-020",
        normalization: REMAINING_PERCENTAGE_NORMALIZATION,
      },
    },
  };
}

export function buildRelationGraphForWidget(
  _kind: "quota",
  representations: ExtractedRepresentation[],
): RelationGraph {
  return buildQuotaRelationGraph(representations);
}
