/**
 * Agent Signal Schema
 *
 * Agents communicate via a trivial JSON signal: done, questions, or error.
 * All structured output is file-based (see file-io.ts).
 */

import { z } from 'zod';

// =============================================================================
// SHARED SCHEMAS
// =============================================================================

const optionSchema = z.object({
  label: z.string(),
  description: z.string().optional(),
});

export const questionItemSchema = z.object({
  id: z.string(),
  question: z.string(),
  options: z.array(optionSchema).optional(),
  multiSelect: z.boolean().optional(),
});

export type QuestionItem = z.infer<typeof questionItemSchema>;

// =============================================================================
// UNIVERSAL SIGNAL SCHEMA
// =============================================================================

export const agentSignalSchema = z.discriminatedUnion('status', [
  z.object({ status: z.literal('done') }),
  z.object({ status: z.literal('questions'), questions: z.array(questionItemSchema) }),
  z.object({ status: z.literal('error'), error: z.string() }),
]);

export type AgentSignal = z.infer<typeof agentSignalSchema>;

export const agentSignalJsonSchema = {
  type: 'object',
  oneOf: [
    {
      properties: {
        status: { const: 'done' },
      },
      required: ['status'],
    },
    {
      properties: {
        status: { const: 'questions' },
        questions: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              id: { type: 'string' },
              question: { type: 'string' },
              options: {
                type: 'array',
                items: {
                  type: 'object',
                  properties: {
                    label: { type: 'string' },
                    description: { type: 'string' },
                  },
                  required: ['label'],
                },
              },
              multiSelect: { type: 'boolean' },
            },
            required: ['id', 'question'],
          },
        },
      },
      required: ['status', 'questions'],
    },
    {
      properties: {
        status: { const: 'error' },
        error: { type: 'string' },
      },
      required: ['status', 'error'],
    },
  ],
};

// =============================================================================
// BACKWARD COMPATIBILITY
// =============================================================================

/** @deprecated Use agentSignalSchema */
export const agentOutputSchema = agentSignalSchema;
/** @deprecated Use AgentSignal */
export type AgentOutput = AgentSignal;
/** @deprecated Use agentSignalJsonSchema */
export const agentOutputJsonSchema = agentSignalJsonSchema;
