import { z } from "zod";
import { executionContextSchema } from "./context.js";
import { scopeRefSchema } from "./coverage.js";
import { artifactRefSchema } from "./finding.js";
import {
  defineRecordCodec,
  recordEnvelopeSchema,
  type RecordCodec,
} from "./envelope.js";

export const HARNESS_OUTCOME_VERSION = "harness-outcome/v1" as const;

export const harnessOutcomeSchema = recordEnvelopeSchema
  .extend({
    schemaVersion: z.literal(HARNESS_OUTCOME_VERSION),
    status: z.literal("harness-failure"),
    phase: z.enum(["setup", "adapter", "detector", "infrastructure"]),
    scope: scopeRefSchema,
    plannedContext: executionContextSchema.optional(),
    cause: z
      .object({
        code: z.string(),
        message: z.string(),
        retryable: z.boolean(),
      })
      .strict(),
    artifactRefs: z.array(artifactRefSchema),
    runId: z.string(),
  })
  .strict();

export type HarnessOutcome = z.infer<typeof harnessOutcomeSchema>;

export const harnessOutcomeCodec: RecordCodec<HarnessOutcome> =
  defineRecordCodec({
    schema: harnessOutcomeSchema,
    currentVersion: HARNESS_OUTCOME_VERSION,
  });
