// Generated by bynkc — do not edit by hand.
// context gauge

import { Ok, Err, Some, None, type Result, type Option, type ValidationError, type DurableObjectState, type DurableObjectNamespace, StateRegistry, makeAgent, rehydrationViolation, type JsonValue, type BoundaryError } from "./runtime.js";

export type Level = number & { readonly __brand: "gauge.Level" };

export const Level = {
  of(value: number): Result<Level, ValidationError> {
    if (!Number.isInteger(value)) {
      return Err({ field: "Level", message: "must be an integer", value });
    }
    if (!(value > 0)) {
      return Err({ field: "Level", message: "must be positive", value });
    }
    return Ok(value as Level);
  },
  unsafe(value: number): Level {
    return value as Level;
  },
};

export interface GaugeState {
  readonly level: Level;
}

const __GaugeRegistry = new StateRegistry();
function __zeroOfGaugeState(): GaugeState { return { level: Level.unsafe(1) }; }

function __rehydrateGaugeState(s: GaugeState): void {
  { const __r = deserialise_Level((s.level as unknown as JsonValue), "level"); if (__r.tag === "Err") throw rehydrationViolation("Gauge", __r.error); }
}

export class Gauge {
  state: DurableObjectState;
  constructor(state: DurableObjectState) {
    this.state = state;
  }

  private async loadState(): Promise<GaugeState> {
    const stored = await this.state.storage.get<GaugeState>("state");
    if (stored === undefined) return __zeroOfGaugeState();
    const __merged = { ...__zeroOfGaugeState(), ...stored };
    __rehydrateGaugeState(__merged);
    return __merged;
  }

  private async commitState(s: GaugeState): Promise<void> {
    await this.state.storage.put("state", s);
  }

  async peek(deps: {}): Promise<Result<void, string>> {
    const __state = await this.loadState();
    return Ok(undefined);
  }

}

export function __makeGauge(key: string, env?: { GAUGE?: DurableObjectNamespace }): Gauge {
  return makeAgent(__GaugeRegistry, env?.GAUGE, key, (state) => new Gauge(state));
}

export function __resetAgents(): void {
  __GaugeRegistry.reset();
}

export function serialise_Level(value: Level): JsonValue {
  return value as unknown as number;
}

export function deserialise_Level(json: JsonValue, path: string = "$"): Result<Level, BoundaryError> {
  if (typeof json !== "number") {
    return Err({ kind: "StructuralMismatch", path, expected: "number", actual: typeof json });
  }
  const validated = (typeof (Level as any).of === "function")
    ? (Level as any).of(json)
    : Ok(json as unknown as Level);
  if (validated.tag === "Err") {
    return Err({ kind: "RefinementViolation", path, violation: validated.error });
  }
  return Ok(validated.value as Level);
}


