import { Type, Static } from '@sinclair/typebox';
import { TodoStore } from '../runtime/todo_store.js';
import { registerSchema } from './catalog.js';

const TodoItemSchema = Type.Object({
  id: Type.String({ description: '唯一标识' }),
  content: Type.String({ description: '任务描述' }),
  status: Type.Union([
    Type.Literal('pending'),
    Type.Literal('in_progress'),
    Type.Literal('completed'),
    Type.Literal('cancelled'),
  ], { description: '当前状态' }),
});

const TodoParams = Type.Object({
  todos: Type.Optional(Type.Array(TodoItemSchema, { description: '任务项数组。省略则读取当前列表。' })),
  merge: Type.Optional(Type.Boolean({ description: 'true=按 id 增量更新。false(默认)=全量替换。', default: false })),
});

export const todoToolSchema = {
  name: 'todo' as const,
  description:
    '管理当前会话的任务列表。用于复杂任务或用户提供多个任务时。\n'
    + '不传参数=读取当前列表。传 todos 数组=写入。\n'
    + 'merge=false(默认)全量替换，merge=true 按 id 增量更新。\n'
    + '列表顺序=优先级。同一时间只能有一个 in_progress。',
  parameters: TodoParams,
};

type TodoExecArgs = Static<typeof TodoParams>;

/** 执行 todo 工具 */
export function executeTodo(
  store: TodoStore,
  args: TodoExecArgs,
): { todos: any[]; summary: any } {
  if (args.todos && args.todos.length > 0) {
    store.write(args.todos, args.merge ?? false);
  }
  return {
    todos: store.read(),
    summary: store.getSummary(),
  };
}

registerSchema({
  name: 'todo',
  toolset: 'planning',
  description: todoToolSchema.description,
  capability: 'text',
  visibility: 'internal',
  isCore: true,
  canDisable: false,
  supportsPromptHint: true,
});
