/**
 * Server 类型定义
 */

import { z } from 'zod';

// ============ Session 相关 ============

export const SessionStatusSchema = z.enum(['idle', 'active', 'busy', 'running', 'paused']);

export const SessionSchema = z.object({
  id: z.string().uuid(),
  name: z.string().optional(),
  workdir: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
  status: SessionStatusSchema,
  messageCount: z.number().int().min(0),
});

export type Session = z.infer<typeof SessionSchema>;
export type SessionStatus = z.infer<typeof SessionStatusSchema>;

export const CreateSessionInputSchema = z.object({
  name: z.string().optional(),
  workdir: z.string().optional(),
});

export type CreateSessionInput = z.infer<typeof CreateSessionInputSchema>;

// ============ Message 相关 ============

export const MessageRoleSchema = z.enum(['user', 'assistant', 'system', 'tool']);

export const MessageSchema = z.object({
  id: z.string().uuid(),
  sessionId: z.string().uuid(),
  role: MessageRoleSchema,
  content: z.string(),
  createdAt: z.string(),
  toolCalls: z
    .array(
      z.object({
        id: z.string(),
        name: z.string(),
        arguments: z.record(z.string(), z.unknown()),
      })
    )
    .optional(),
  toolResults: z
    .array(
      z.object({
        toolCallId: z.string(),
        result: z.unknown(),
      })
    )
    .optional(),
});

export type Message = z.infer<typeof MessageSchema>;

export const SendMessageInputSchema = z.object({
  role: MessageRoleSchema.default('user'),
  content: z.string().min(1),
  stream: z.boolean().optional().default(true),
});

export type SendMessageInput = z.infer<typeof SendMessageInputSchema>;

// ============ Tool 相关 ============

export const ToolSchema = z.object({
  name: z.string(),
  description: z.string(),
  category: z.string().optional(),
  parameters: z.record(
    z.string(),
    z.object({
      type: z.string(),
      description: z.string(),
      required: z.boolean().optional(),
    })
  ),
});

export type Tool = z.infer<typeof ToolSchema>;

// ============ WebSocket 消息 ============

// Agent 模式类型
export type AgentModeType = 'build' | 'plan';

// 客户端发送的消息
export interface ClientMessage {
  type: 'message' | 'cancel' | 'tool_response' | 'permission_response' | 'config_update' | 'mode_switch';
  sessionId: string;
  payload?: {
    content?: string;
    toolCallId?: string;
    approved?: boolean;
    // Permission response fields
    requestId?: string;
    allow?: boolean;
    remember?: boolean;
    // Agent mode fields
    agentMode?: AgentModeType;
    autoApprove?: boolean;
  };
}

// 服务端发送的消息
export interface ServerMessage {
  type:
    | 'connected'
    | 'message_received'
    | 'chunk'
    | 'tool_call'
    | 'tool_result'
    | 'tool_start'    // 工具开始执行
    | 'tool_end'      // 工具执行完成
    | 'done'
    | 'cancelled'
    | 'error'
    | 'session_updated'
    | 'permission_request'
    | 'mode_switched'; // 模式切换完成
  sessionId: string;
  payload?: unknown;
}

// 工具开始事件 Payload
export interface ToolStartPayload {
  id: string;
  toolName: string;
  arguments: Record<string, unknown>;
}

// 工具结束事件 Payload
export interface ToolEndPayload {
  id: string;
  status: 'completed' | 'error';
  result?: unknown;
  error?: string;
  duration?: number;
}

// ============ Permission 相关 ============

export type PermissionType = 'bash' | 'file' | 'git' | 'web';

/**
 * 权限请求上下文
 */
export interface PermissionRequestContext {
  command?: string;           // bash 命令
  operation?: string;         // 文件操作类型: read/write/edit/delete
  path?: string;              // 文件路径
  gitOperation?: string;      // git 操作
  query?: string;             // web 查询
  patterns?: string[];        // 匹配模式
  externalPaths?: string[];   // 外部路径
}

/**
 * Diff 信息（文件写入/编辑时）
 */
export interface DiffHunkInfo {
  oldStart: number;
  oldCount: number;
  newStart: number;
  newCount: number;
  lines: Array<{
    type: 'add' | 'remove' | 'context';
    lineNumber: number | null;
    content: string;
  }>;
}

export interface DiffInfo {
  isNew: boolean;
  additions: number;
  deletions: number;
  hunks: DiffHunkInfo[];
}

/**
 * 权限请求消息 payload
 */
export interface PermissionRequestPayload {
  requestId: string;
  permissionType: PermissionType;
  context: PermissionRequestContext;
  diff?: DiffInfo;
}

/**
 * 权限响应消息 payload
 */
export interface PermissionResponsePayload {
  requestId: string;
  allow: boolean;
  remember?: boolean;
}

// ============ SSE 事件 ============

export interface SSEEvent {
  event?: 'connected' | 'heartbeat' | 'status' | 'log' | 'progress' | 'file_change' | 'tool_execution';
  data: {
    timestamp: number;
    sessionId?: string;
    payload: unknown;
  };
}

// ============ 消息 Parts 相关 ============

/**
 * 工具调用状态
 */
export type ToolCallStatus = 'pending' | 'running' | 'completed' | 'error';

/**
 * 文本 Part
 */
export interface TextMessagePart {
  type: 'text';
  id: string;
  text: string;
}

/**
 * 工具调用 Part
 */
export interface ToolMessagePart {
  type: 'tool';
  id: string;
  toolCallId: string;
  toolName: string;
  status: ToolCallStatus;
  arguments: Record<string, unknown>;
  result?: unknown;
  error?: string;
  duration?: number;
}

/**
 * 推理 Part
 */
export interface ReasoningMessagePart {
  type: 'reasoning';
  id: string;
  text: string;
}

/**
 * 消息 Part 联合类型
 */
export type MessagePart = TextMessagePart | ToolMessagePart | ReasoningMessagePart;

/**
 * 工具调用信息（兼容字段，合并后）
 */
export interface ToolCallInfo {
  id: string;
  name: string;
  arguments: Record<string, unknown>;
  status: ToolCallStatus;
  result?: unknown;
  error?: string;
  duration?: number;
}

/**
 * 消息格式（包含有序 Parts）
 *
 * 只有 user 和 assistant 两种角色：
 * - user: 用户输入
 * - assistant: AI 回复（包含文本和工具调用，按原始顺序）
 */
export interface MergedMessage {
  id: string;
  sessionId: string;
  role: 'user' | 'assistant';
  timestamp: string;
  /** 有序的消息内容 Parts */
  parts: MessagePart[];
  /** 所有文本拼接（兼容字段） */
  content?: string;
  /** 所有工具调用（兼容字段） */
  toolCalls?: ToolCallInfo[];
  metadata?: {
    model?: string;
    stepCount?: number;
    totalTokens?: number;
  };
}

// ============ API 响应 ============

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
}

export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
  hasMore: boolean;
}

// ============ Command 相关 ============

export interface CommandInfo {
  name: string;
  description?: string;
  agent?: string;
  model?: string;
  subtask?: boolean;
  source: 'builtin' | 'user' | 'project';
  hasTemplate: boolean;
}

export interface CommandSearchResult {
  name: string;
  description?: string;
  source: string;
  score: number;
}

export interface CommandExecuteResult {
  prompt: string;
  agent?: string;
  model?: string;
  subtask?: boolean;
}

export interface CommandListResponse {
  commands: Array<{
    name: string;
    description?: string;
    source: string;
  }>;
  stats: {
    total: number;
    bySource: Record<string, number>;
  };
}
