/**
 * Self-contained `emit()` helper copied verbatim into a target repo's
 * `.seeflow/sdk/emit.ts` by `seeflow register` when the demo declares any
 * event-bound state node. Kept dependency-free so the user's app can call it
 * without installing `@seeflow/sdk`.
 */
export const EMIT_TEMPLATE = `// Auto-generated by seeflow register. Safe to commit; safe to delete.
// Re-running register will not overwrite this file.
export type EmitStatus = 'running' | 'done' | 'error';

export interface EmitOptions {
  runId?: string;
  payload?: unknown;
  studioUrl?: string;
}

const readEnv = (key: string): string | undefined => {
  const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;
  return proc?.env?.[key];
};

export async function emit(
  flowId: string,
  nodeId: string,
  status: EmitStatus,
  opts: EmitOptions = {},
): Promise<void> {
  const base = (
    opts.studioUrl ?? readEnv('SEEFLOW_STUDIO_URL') ?? 'http://localhost:4321'
  ).replace(/\\/+$/, '');
  await fetch(\`\${base}/api/emit\`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ flowId, nodeId, status, runId: opts.runId, payload: opts.payload }),
  });
}
`;
