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

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 Light =
    { readonly tag: "Red" }
  | { readonly tag: "Green" };

export const Light = {
  Red: { tag: "Red" } as Light,
  Green: { tag: "Green" } as Light,
};

export interface SignalState {
  readonly colour: Light;
}

const __SignalRegistry = new StateRegistry();
function __zeroOfSignalState(): SignalState { return { colour: Light.Red }; }

function __rehydrateSignalState(s: SignalState): void {
  { const __r = deserialise_Light((s.colour as unknown as JsonValue), "colour"); if (__r.tag === "Err") throw rehydrationViolation("Signal", __r.error); }
}

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

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

  private async commitState(s: SignalState): 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 __makeSignal(key: string, env?: { SIGNAL?: DurableObjectNamespace }): Signal {
  return makeAgent(__SignalRegistry, env?.SIGNAL, key, (state) => new Signal(state));
}

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

export function serialise_Light(value: Light): JsonValue {
  switch (value.tag) {
    case "Red":
      return { kind: "Red" };
    case "Green":
      return { kind: "Green" };
  }
}

export function deserialise_Light(json: JsonValue, path: string = "$"): Result<Light, BoundaryError> {
  if (typeof json !== "object" || json === null || Array.isArray(json)) {
    return Err({ kind: "StructuralMismatch", path, expected: "object", actual: typeof json });
  }
  const obj = json as { [k: string]: JsonValue };
  const kind = obj["kind"];
  switch (kind) {
    case "Red":
      return Ok({ tag: "Red" } as Light);
    case "Green":
      return Ok({ tag: "Green" } as Light);
    default:
      return Err({ kind: "StructuralMismatch", path, expected: "sum variant kind", actual: String(kind) });
  }
}


