export type CaseRunStatus = "queued" | "running" | "completed" | "failed" | "blocked" | "cancel_requested" | "canceled";

export type CaseRunEvent = {
  id: number;
  runId: string;
  status: CaseRunStatus;
  stage: string;
  payload: Record<string, unknown>;
  createdAt: string;
};

export type CaseRunRecord = {
  runId: string;
  caseId: string;
  workflowId: string;
  workflowRunId: string | null;
  status: CaseRunStatus;
  stage: string;
  terminal: boolean;
  caseRepo: string;
  runDir: string;
  runtimeApiUrl: string;
  result: Record<string, unknown> | null;
  error: { code: string; message: string; details?: unknown } | null;
  blocker: Record<string, unknown> | null;
  createdAt: string;
  updatedAt: string;
};

export type StartCaseRunInput = {
  runId: string;
  caseId: string;
  workflowId: string;
  caseRepo: string;
  runDir: string;
  runtimeApiUrl: string;
};

export type ListCaseRunsInput = {
  limit: number;
  status?: CaseRunStatus;
  before?: { createdAt: string; runId: string };
};

export type CaseRunListItem = {
  runId: string;
  caseId: string;
  workflowId: string;
  workflowRunId: string | null;
  status: CaseRunStatus;
  stage: string;
  terminal: boolean;
  createdAt: string;
  updatedAt: string;
  artifactCount: number;
  evidenceStatus: string | null;
  artifactManifestSha256: string | null;
};

export type ActivityResult = {
  runId: string;
  activityName: string;
  identity: string;
  output: Record<string, unknown>;
};

export interface HarnessRLRegistry {
  ensureSchema(): Promise<void>;
  createRun(input: StartCaseRunInput): Promise<CaseRunRecord>;
  getRun(runId: string): Promise<CaseRunRecord | null>;
  listRuns(input: ListCaseRunsInput): Promise<CaseRunRecord[]>;
  updateRun(runId: string, patch: Partial<Pick<CaseRunRecord, "workflowRunId" | "status" | "stage" | "result" | "error" | "blocker">>): Promise<CaseRunRecord>;
  appendEvent(runId: string, status: CaseRunStatus, stage: string, payload?: Record<string, unknown>): Promise<CaseRunEvent>;
  listEvents(runId: string): Promise<CaseRunEvent[]>;
  getActivityResult(runId: string, activityName: string, identity: string): Promise<ActivityResult | null>;
  saveActivityResult(result: ActivityResult): Promise<ActivityResult>;
  health(): Promise<{ ok: true }>;
  close(): Promise<void>;
}

export interface HarnessRLTemporalGateway {
  start(input: { workflowId: string; runId: string }): Promise<{ workflowRunId: string; reused?: boolean }>;
  requestCancel(workflowId: string): Promise<void>;
  close(): Promise<void>;
}

export function terminalStatus(status: CaseRunStatus) {
  return status === "completed" || status === "failed" || status === "blocked" || status === "canceled";
}
