import { z } from 'zod/v4';

export const FEEDBACK_KEY = '__feedback__';

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

const sharedFieldProps = {
  label: z.string(),
  description: z.string().optional(),
  required: z.boolean().optional(),
};

const humanInputTodoItemSchema = z.object({
  id: z.string(),
  content: z.string(),
});

const humanInputFieldSchema = z.discriminatedUnion('type', [
  z.object({
    ...sharedFieldProps,
    type: z.enum(['text', 'textarea', 'number', 'email', 'url', 'tel']),
  }),
  z.object({
    ...sharedFieldProps,
    type: z.enum(['single_select', 'multi_select']),
    options: z.array(humanInputOptionSchema).min(2),
  }),
  z.object({
    ...sharedFieldProps,
    type: z.literal('yes_no'),
    options: z.array(humanInputOptionSchema).length(2).optional(),
  }),
  z.object({
    ...sharedFieldProps,
    type: z.literal('todo_list'),
    initialTodos: z.array(humanInputTodoItemSchema).optional(),
    minItems: z.number().int().min(0).optional(),
    maxItems: z.number().int().min(1).optional(),
  }),
]);

export type HumanInputTodoItem = z.infer<typeof humanInputTodoItemSchema>;

const humanInputResponseSchema = z.object({
  value: z.union([z.string(), z.array(z.string())]),
  respondedBy: z.string(),
  timestamp: z.number(),
});

export type HumanInputResponse = z.infer<typeof humanInputResponseSchema>;

export const humanInputRequestMetadataSchema = z.object({
  question: z.string(),
  context: z.string().optional(),
  fields: z.array(humanInputFieldSchema).min(1),
  requestedAt: z.number(),
  response: humanInputResponseSchema.optional(),
  /** Superseded answers, oldest first — appended on each edit so the card
   *  can flip through response versions. */
  responseHistory: z.array(humanInputResponseSchema).optional(),
});

export type HumanInputField = z.infer<typeof humanInputFieldSchema>;
export type HumanInputRequestMetadata = z.infer<
  typeof humanInputRequestMetadataSchema
>;

const locationResponseSchema = z.object({
  location: z.string(),
  respondedBy: z.string(),
  timestamp: z.number(),
});

export const locationRequestMetadataSchema = z.object({
  reason: z.string(),
  requestedAt: z.number(),
  response: locationResponseSchema.optional(),
  denied: z.boolean().optional(),
});

export type LocationRequestMetadata = z.infer<
  typeof locationRequestMetadataSchema
>;
