import { z } from 'zod';

export const LLM_TYPES = ['anthropic', 'openai', 'deepseek', 'vllm', 'ollama', 'gemini-cli'] as const;
export const LLM_TIERS = ['fast', 'heavy'] as const;

/**
 * Reference to a key inside a Secret. `name` is the Secret resource name;
 * `key` is the JSON key inside that secret's `data` map. mcpd resolves the
 * pair through SecretService at inference time, so credentials never leave
 * the server.
 */
export const ApiKeyRefSchema = z.object({
  name: z.string().min(1),
  key: z.string().min(1),
});

/**
 * v4: pool key. Same character set as `name` (lowercase + digits + hyphens)
 * because at the CLI/yaml level the two share a namespace — agents and
 * operators read both interchangeably and a stray uppercase or underscore
 * here would be a confusing footgun. Empty string is rejected; use `null`
 * (or omit the field) to declare "pool of 1, fall back to name".
 */
const PoolNameSchema = z.string().min(1).max(100).regex(/^[a-z0-9-]+$/, 'poolName must be lowercase alphanumeric with hyphens');

export const CreateLlmSchema = z.object({
  name: z.string().min(1).max(100).regex(/^[a-z0-9-]+$/, 'Name must be lowercase alphanumeric with hyphens'),
  type: z.enum(LLM_TYPES),
  model: z.string().min(1),
  url: z.string().url().optional(),
  tier: z.enum(LLM_TIERS).default('fast'),
  description: z.string().max(500).default(''),
  apiKeyRef: ApiKeyRefSchema.optional(),
  extraConfig: z.record(z.unknown()).default({}),
  poolName: PoolNameSchema.nullable().optional(),
});

export const UpdateLlmSchema = z.object({
  model: z.string().min(1).optional(),
  url: z.string().url().or(z.literal('')).optional(),
  tier: z.enum(LLM_TIERS).optional(),
  description: z.string().max(500).optional(),
  apiKeyRef: ApiKeyRefSchema.nullable().optional(),
  extraConfig: z.record(z.unknown()).optional(),
  poolName: PoolNameSchema.nullable().optional(),
});

export type CreateLlmInput = z.infer<typeof CreateLlmSchema>;
export type UpdateLlmInput = z.infer<typeof UpdateLlmSchema>;
export type ApiKeyRef = z.infer<typeof ApiKeyRefSchema>;
