import {
  runStepsCreate,
  runStepsUpdate,
  runsCreate,
  runsUpdate,
} from '../../lib/platform-client.js';
import type { PlatformClientOptions } from '../../lib/platform-client.js';

interface TrackRunInput {
  runId: string;
  productId: string;
  name: string;
  initiatedBy?: string;
  requestId?: string;
  token?: string;
  input?: Record<string, unknown>;
}

interface TrackStepInput {
  runId: string;
  productId: string;
  stepName: string;
  order: number;
  token?: string;
  requestId?: string;
  input?: Record<string, unknown>;
  output?: Record<string, unknown>;
  error?: string;
}

export async function trackRunStarted(input: TrackRunInput): Promise<void> {
  await runsCreate(
    {
      id: input.runId,
      kind: 'agent',
      name: input.name,
      source: 'mcp.a2a',
      triggeredBy: input.initiatedBy,
      input: input.input,
      metadata: {
        productId: input.productId,
      },
    },
    buildOptions(input)
  );
}

export async function trackRunCompleted(
  input: TrackRunInput & { output?: Record<string, unknown> }
): Promise<void> {
  await runsUpdate(
    input.runId,
    {
      status: 'succeeded',
      output: input.output,
    },
    buildOptions(input)
  );
}

export async function trackRunFailed(
  input: TrackRunInput & { error: string; output?: Record<string, unknown> }
): Promise<void> {
  await runsUpdate(
    input.runId,
    {
      status: 'failed',
      error: input.error,
      output: input.output,
    },
    buildOptions(input)
  );
}

export async function trackStepStarted(input: TrackStepInput): Promise<void> {
  await runStepsCreate(
    input.runId,
    {
      stepName: input.stepName,
      order: input.order,
      input: input.input,
    },
    buildOptions(input)
  );
}

export async function trackStepCompleted(input: TrackStepInput): Promise<void> {
  await runStepsUpdate(
    input.runId,
    input.stepName,
    {
      status: 'succeeded',
      output: input.output,
    },
    buildOptions(input)
  );
}

export async function trackStepFailed(input: TrackStepInput): Promise<void> {
  await runStepsUpdate(
    input.runId,
    input.stepName,
    {
      status: 'failed',
      error: input.error ?? 'Step failed',
      output: input.output,
    },
    buildOptions(input)
  );
}

function buildOptions(input: {
  token?: string;
  requestId?: string;
  productId: string;
}): PlatformClientOptions {
  return {
    token: input.token,
    requestId: input.requestId,
    productId: input.productId,
  };
}
