// Generated by bynkc — do not edit by hand.
// context demo.agt

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

export type Counter = number & { readonly __brand: "demo.agt.Counter" };

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

export interface BoxState {
  readonly n: number;
}

const __BoxRegistry = new StateRegistry();
function __zeroOfBoxState(): BoxState { return { n: 0 }; }

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

  private async loadState(): Promise<BoxState> {
    const stored = await this.state.storage.get<BoxState>("state");
    return stored ?? __zeroOfBoxState();
  }

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

  async read(deps: {}): Promise<number> {
    const currentState = await this.loadState();
    return currentState.n;
  }

}

export function __makeBox(key: Counter, env?: { BOX?: DurableObjectNamespace }): Box {
  return makeAgent(__BoxRegistry, env?.BOX, key, (state) => new Box(state));
}

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

