import {
  IsArray,
  IsBoolean,
  IsInt,
  IsIn,
  IsObject,
  IsOptional,
  IsString,
  IsUUID,
  MaxLength,
  Min,
  ValidateNested,
  ArrayNotEmpty,
} from 'class-validator';
import { Type } from 'class-transformer';

// ─── Condition DTO ────────────────────────────────────────────────────────────

const conditionFields = [
  'taskType',
  'complexity',
  'domain',
  'costTier',
  'requiredCapabilities',
] as const;
const conditionOperators = ['eq', 'in', 'includes'] as const;

export class RoutingConditionDto {
  @IsString()
  @IsIn(conditionFields)
  field!: (typeof conditionFields)[number];

  @IsString()
  @IsIn(conditionOperators)
  operator!: (typeof conditionOperators)[number];

  // value can be string or string[] — keep as unknown and validate at runtime
  value!: string | string[];
}

// ─── Action DTO ───────────────────────────────────────────────────────────────

export class RoutingActionDto {
  @IsString()
  @MaxLength(255)
  provider!: string;

  @IsString()
  @MaxLength(255)
  model!: string;

  @IsOptional()
  @IsUUID()
  agentConfigId?: string;

  @IsOptional()
  @IsString()
  @MaxLength(50_000)
  systemPromptOverride?: string;

  @IsOptional()
  @IsArray()
  toolAllowlist?: string[];
}

// ─── Create DTO ───────────────────────────────────────────────────────────────

const scopeValues = ['system', 'user'] as const;

export class CreateRoutingRuleDto {
  @IsString()
  @MaxLength(255)
  name!: string;

  @IsInt()
  @Min(0)
  priority!: number;

  @IsOptional()
  @IsIn(scopeValues)
  scope?: 'system' | 'user';

  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => RoutingConditionDto)
  conditions!: RoutingConditionDto[];

  @IsObject()
  @ValidateNested()
  @Type(() => RoutingActionDto)
  action!: RoutingActionDto;

  @IsOptional()
  @IsBoolean()
  enabled?: boolean;
}

// ─── Update DTO ───────────────────────────────────────────────────────────────

export class UpdateRoutingRuleDto {
  @IsOptional()
  @IsString()
  @MaxLength(255)
  name?: string;

  @IsOptional()
  @IsInt()
  @Min(0)
  priority?: number;

  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => RoutingConditionDto)
  conditions?: RoutingConditionDto[];

  @IsOptional()
  @IsObject()
  @ValidateNested()
  @Type(() => RoutingActionDto)
  action?: RoutingActionDto;

  @IsOptional()
  @IsBoolean()
  enabled?: boolean;
}

// ─── Reorder DTO ──────────────────────────────────────────────────────────────

export class ReorderRoutingRulesDto {
  @IsArray()
  @ArrayNotEmpty()
  @IsUUID(undefined, { each: true })
  ruleIds!: string[];
}
