// src/querypad/QueryPad.ts

import type { IMatrixContext } from '../engine/core/IMatrixContext';
import {
  createFlowContext,
  FlowContext,
  type IFlowContextData,
} from '../flow/FlowContext';
import { FlowBuilder } from '../flow/FlowBuilder';

/**
 * Thin facade that gives a "LINQPad-style" API for building flows
 * against a given context.
 */
export class QueryPad {
  private readonly context: IMatrixContext;
  private readonly baseContext: FlowContext;

  private constructor(context: IMatrixContext, ctx: FlowContext) {
    this.context = context;
    this.baseContext = ctx;
  }

  /**
   * Create a QueryPad for an IMatrixContext.
   */
  static forContext(
    context: IMatrixContext,
    seed?: Partial<IFlowContextData>
  ): QueryPad {
    const ctx = createFlowContext(seed);
    return new QueryPad(context, ctx);
  }

  /**
   * Start a new flow bound to this QueryPad's base FlowContext.
   */
  flow<TIn = unknown>(): FlowBuilder<TIn, TIn> {
    // Create a new context with same traceId but a distinct flowId
    // This ensures flows from the same QueryPad share a trace but have unique flowIds
    const ctx = createFlowContext({
      traceId: this.baseContext.traceId,
      flowId: undefined, // Force generation of a new flowId
      userId: this.baseContext.userId,
      attributes: this.baseContext.attributes,
    });

    return FlowBuilder.start<TIn>(this.context, ctx);
  }
}
