import { SCHEMA_VERSION } from "./constants.js";
import type { RuntimeContext } from "./types.js";

export function json(value: unknown): void {
  process.stdout.write(`${JSON.stringify(value)}\n`);
}

export function generatedAt(): string {
  return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
}

export function success(summary: string, data: unknown, ctx: RuntimeContext, durationMs: number, nextCommands: string[] = []): void {
  json({
    ok: true,
    schema_version: SCHEMA_VERSION,
    summary,
    data,
    metadata: {
      request_id: ctx.requestId,
      server: ctx.server,
      duration_ms: durationMs,
      generated_at: generatedAt(),
    },
    next_commands: nextCommands,
  });
}

export function failure({
  summary,
  code,
  message,
  retryable = false,
  server = null,
  requestId = null,
  data = null,
  nextCommands = [],
}: {
  summary: string;
  code: string;
  message: string;
  retryable?: boolean;
  server?: string | null;
  requestId?: string | null;
  data?: unknown;
  nextCommands?: string[];
}): void {
  json({
    ok: false,
    schema_version: SCHEMA_VERSION,
    summary,
    error: { code, message, retryable },
    data,
    metadata: {
      request_id: requestId,
      server,
      generated_at: generatedAt(),
    },
    next_commands: nextCommands,
  });
}

