/**
 * Agent Type Form Validation Schemas
 *
 * Zod schemas for validating agent type form data.
 * Used with react-hook-form for form validation.
 */

import { z } from 'zod';
import type { AgentTypeCategory } from '@/lib/api/types/agentTypes';

/**
 * Slug validation regex: lowercase letters, numbers, and hyphens only
 */
const slugRegex = /^[a-z0-9-]+$/;

/**
 * Hex color validation regex
 */
const hexColorRegex = /^#[0-9A-Fa-f]{6}$/;

/**
 * Available AI models for agent types
 */
/* istanbul ignore next -- constant declaration */
export const AVAILABLE_MODELS = [
  { value: 'claude-opus-4-5-20251101', label: 'Claude Opus 4.5' },
  { value: 'claude-sonnet-4-20250514', label: 'Claude Sonnet 4' },
  { value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' },
] as const;

/**
 * Available MCP servers for agent permissions
 */
/* istanbul ignore next -- constant declaration */
export const AVAILABLE_MCP_SERVERS = [
  { id: 'gitea', name: 'Gitea', description: 'Git repository management' },
  { id: 'knowledge', name: 'Knowledge Base', description: 'Vector database for RAG' },
  { id: 'filesystem', name: 'Filesystem', description: 'File read/write operations' },
  { id: 'slack', name: 'Slack', description: 'Team communication' },
  { id: 'browser', name: 'Browser', description: 'Web browsing and scraping' },
] as const;

/**
 * Agent type status options
 */
/* istanbul ignore next -- constant declaration */
export const AGENT_TYPE_STATUS = [
  { value: true, label: 'Active' },
  { value: false, label: 'Inactive' },
] as const;

/**
 * Agent type categories for organizing agents
 */
/* istanbul ignore next -- constant declaration */
export const AGENT_TYPE_CATEGORIES: {
  value: AgentTypeCategory;
  label: string;
  description: string;
}[] = [
  { value: 'development', label: 'Development', description: 'Product, project, and engineering' },
  { value: 'design', label: 'Design', description: 'UI/UX and design research' },
  { value: 'quality', label: 'Quality', description: 'QA and security assurance' },
  { value: 'operations', label: 'Operations', description: 'DevOps and MLOps engineering' },
  { value: 'ai_ml', label: 'AI & ML', description: 'Machine learning specialists' },
  { value: 'data', label: 'Data', description: 'Data science and engineering' },
  { value: 'leadership', label: 'Leadership', description: 'Technical leadership' },
  { value: 'domain_expert', label: 'Domain Experts', description: 'Industry specialists' },
];

/**
 * Available Lucide icons for agent types
 */
/* istanbul ignore next -- constant declaration */
export const AVAILABLE_ICONS = [
  // Development
  { value: 'clipboard-check', label: 'Clipboard Check', category: 'development' },
  { value: 'briefcase', label: 'Briefcase', category: 'development' },
  { value: 'file-text', label: 'File Text', category: 'development' },
  { value: 'git-branch', label: 'Git Branch', category: 'development' },
  { value: 'code', label: 'Code', category: 'development' },
  { value: 'server', label: 'Server', category: 'development' },
  { value: 'layout', label: 'Layout', category: 'development' },
  { value: 'smartphone', label: 'Smartphone', category: 'development' },
  // Design
  { value: 'palette', label: 'Palette', category: 'design' },
  { value: 'search', label: 'Search', category: 'design' },
  // Quality
  { value: 'shield', label: 'Shield', category: 'quality' },
  { value: 'shield-check', label: 'Shield Check', category: 'quality' },
  // Operations
  { value: 'settings', label: 'Settings', category: 'operations' },
  { value: 'settings-2', label: 'Settings 2', category: 'operations' },
  // AI/ML
  { value: 'brain', label: 'Brain', category: 'ai_ml' },
  { value: 'microscope', label: 'Microscope', category: 'ai_ml' },
  { value: 'eye', label: 'Eye', category: 'ai_ml' },
  { value: 'message-square', label: 'Message Square', category: 'ai_ml' },
  // Data
  { value: 'bar-chart', label: 'Bar Chart', category: 'data' },
  { value: 'database', label: 'Database', category: 'data' },
  // Leadership
  { value: 'users', label: 'Users', category: 'leadership' },
  { value: 'target', label: 'Target', category: 'leadership' },
  // Domain Expert
  { value: 'calculator', label: 'Calculator', category: 'domain_expert' },
  { value: 'heart-pulse', label: 'Heart Pulse', category: 'domain_expert' },
  { value: 'flask-conical', label: 'Flask', category: 'domain_expert' },
  { value: 'lightbulb', label: 'Lightbulb', category: 'domain_expert' },
  { value: 'book-open', label: 'Book Open', category: 'domain_expert' },
  // Generic
  { value: 'bot', label: 'Bot', category: 'generic' },
] as const;

/**
 * Color palette for agent type visual distinction
 */
/* istanbul ignore next -- constant declaration */
export const COLOR_PALETTE = [
  { value: '#3B82F6', label: 'Blue', category: 'development' },
  { value: '#EC4899', label: 'Pink', category: 'design' },
  { value: '#10B981', label: 'Green', category: 'quality' },
  { value: '#F59E0B', label: 'Amber', category: 'operations' },
  { value: '#8B5CF6', label: 'Purple', category: 'ai_ml' },
  { value: '#06B6D4', label: 'Cyan', category: 'data' },
  { value: '#F97316', label: 'Orange', category: 'leadership' },
  { value: '#84CC16', label: 'Lime', category: 'domain_expert' },
] as const;

/**
 * Model params schema
 */
const modelParamsSchema = z.object({
  temperature: z.number().min(0).max(2),
  max_tokens: z.number().int().min(1024).max(128000),
  top_p: z.number().min(0).max(1),
});

/**
 * Agent type category enum values
 */
const agentTypeCategoryValues = [
  'development',
  'design',
  'quality',
  'operations',
  'ai_ml',
  'data',
  'leadership',
  'domain_expert',
] as const;

/**
 * Schema for agent type form fields
 */
export const agentTypeFormSchema = z.object({
  name: z.string().min(1, 'Name is required').max(255, 'Name must be less than 255 characters'),

  slug: z
    .string()
    .min(1, 'Slug is required')
    .max(255, 'Slug must be less than 255 characters')
    .regex(slugRegex, 'Slug must contain only lowercase letters, numbers, and hyphens')
    /* istanbul ignore next -- edge case validators */
    .refine((val) => !val.startsWith('-') && !val.endsWith('-'), {
      message: 'Slug cannot start or end with a hyphen',
    })
    /* istanbul ignore next -- edge case validators */
    .refine((val) => !val.includes('--'), {
      message: 'Slug cannot contain consecutive hyphens',
    }),

  description: z
    .string()
    .max(2000, 'Description must be less than 2000 characters')
    .nullable()
    .optional(),

  expertise: z.array(z.string()),

  personality_prompt: z
    .string()
    .min(1, 'Personality prompt is required')
    .max(10000, 'Personality prompt must be less than 10000 characters'),

  primary_model: z.string().min(1, 'Primary model is required'),

  fallback_models: z.array(z.string()),

  model_params: modelParamsSchema,

  mcp_servers: z.array(z.string()),

  tool_permissions: z.record(z.string(), z.unknown()),

  is_active: z.boolean(),

  // Category and display fields
  category: z.enum(agentTypeCategoryValues).nullable().optional(),

  icon: z.string().max(50, 'Icon must be less than 50 characters').nullable().optional(),

  color: z
    .string()
    .regex(hexColorRegex, 'Color must be a valid hex code (e.g., #3B82F6)')
    .nullable()
    .optional(),

  sort_order: z.number().int().min(0).max(1000),

  typical_tasks: z.array(z.string()),

  collaboration_hints: z.array(z.string()),
});

/**
 * Schema for creating a new agent type (alias for backward compatibility)
 */
export const agentTypeCreateSchema = agentTypeFormSchema;

/**
 * Schema for updating an existing agent type
 * All fields are optional since we support partial updates
 */
export const agentTypeUpdateSchema = agentTypeFormSchema.partial();

/**
 * Type for agent type create form values
 */
export type AgentTypeCreateFormValues = z.infer<typeof agentTypeCreateSchema>;

/**
 * Type for agent type update form values
 */
export type AgentTypeUpdateFormValues = z.infer<typeof agentTypeUpdateSchema>;

/**
 * Default values for creating a new agent type
 */
export const defaultAgentTypeValues: AgentTypeCreateFormValues = {
  name: '',
  slug: '',
  description: null,
  expertise: [],
  personality_prompt: '',
  primary_model: 'claude-opus-4-5-20251101',
  fallback_models: ['claude-sonnet-4-20250514'],
  model_params: {
    temperature: 0.7,
    max_tokens: 8192,
    top_p: 0.95,
  },
  mcp_servers: [],
  tool_permissions: {},
  is_active: false, // Start as draft
  // Category and display fields
  category: null,
  icon: 'bot',
  color: '#3B82F6',
  sort_order: 0,
  typical_tasks: [],
  collaboration_hints: [],
};

/**
 * Generate slug from name
 *
 * @param name - The name to convert to a slug
 * @returns A valid slug string
 */
export function generateSlug(name: string): string {
  return name
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-') // Replace multiple hyphens with single
    .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
}
