import { BaseEntity } from '../../base/entity/base.js';
import { Column, Entity, Index } from 'typeorm';
import type { AgentMemoryConfig } from '../memory/provider.js';
import type { AgentSessionTreeConfig } from '../session-tree/factory.js';

export interface NetaClawAgentMiddlewareConfig {
  maxToolRounds?: number;
  maxToolCalls?: number;
}

export interface NetaClawAgentThinkingConfig {
  defaultLevel?: 'off' | 'low' | 'medium' | 'high';
}

export interface NetaClawAgentRuntimeConfig {
  memory?: AgentMemoryConfig;
  session?: AgentSessionTreeConfig & {
    restoreLastSession?: boolean;
  };
  middleware?: NetaClawAgentMiddlewareConfig;
  thinking?: NetaClawAgentThinkingConfig;
  temperature?: number;
  maxTokens?: number;
  [key: string]: unknown;
}

/**
 * NetaClaw Agent 配置
 */
@Entity('netaclaw_agent')
export class NetaClawAgentEntity extends BaseEntity {
  @Column({ comment: '唯一标识', length: 100, unique: true })
  name: string;

  @Column({ comment: '显示名称', length: 200 })
  label: string;

  @Column({ comment: '描述', type: 'text', nullable: true })
  description: string;

  @Column({ comment: '图标', length: 100, nullable: true })
  icon: string;

  @Column({ comment: '系统提示词', type: 'text', nullable: true })
  systemPrompt: string;

  @Column({ type: 'json', comment: '关联Skill名称列表', nullable: true })
  skills: string[];

  @Column({ type: 'json', comment: '启用的toolset列表', nullable: true })
  toolsets: string[];

  @Column({ type: 'json', comment: '工具精细配置', nullable: true })
  tools: {
    inheritCoreTools?: boolean;
    enabled?: string[];
    disabled?: string[];
    perTool?: Record<string, {
      enabled?: boolean;
      promptHint?: string;
      allowInSubagent?: boolean;
      workerRoutingStrategy?: 'auto' | 'force-local' | 'force-main-process-proxy' | 'force-disabled';
    }>;
  };

  @Column({ type: 'json', comment: '模型配置', nullable: true })
  modelConfig: { apiUrl?: string; apiKey?: string; modelId?: string; contextWindow?: number };

  @Column({ type: 'json', comment: 'Agent配置', nullable: true })
  config: NetaClawAgentRuntimeConfig;

  @Column({ type: 'json', comment: 'Subagent閰嶇疆', nullable: true })
  subagentConfig: {
    enabled?: boolean;
    maxConcurrent?: number;
    allowedPresetAgentIds?: number[];
    allowedToolNames?: string[];
  };

  @Index()
  @Column({ comment: '状态: 0=草稿 1=已发布', default: 0 })
  status: number;

  @Column({ comment: '是否可作为集群主 Agent', default: 0 })
  isCrewMaster: number;

  @Column({ comment: '辅助模型渠道ID', nullable: true })
  auxiliaryModelChannelId: number;

  @Column({ comment: '辅助模型ID', nullable: true })
  auxiliaryModelId: string;

  @Column({ comment: '自动压缩阈值百分比 0=禁用', default: 70 })
  compactionThreshold: number;

  @Column({ comment: '压缩保留最近N条消息', default: 4 })
  compactionKeepRecent: number;
}
