/**
 * TodoStore - 会话级任务列表管理
 * 参考 hermes-agent-main 的 TodoStore 设计
 */

export interface TodoItem {
  id: string;
  content: string;
  status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
}

export interface TodoSummary {
  total: number;
  pending: number;
  in_progress: number;
  completed: number;
  cancelled: number;
}

const VALID_STATUSES = ['pending', 'in_progress', 'completed', 'cancelled'];

export class TodoStore {
  private items: TodoItem[] = [];

  /**
   * 写入 todo 列表
   * @param todos 任务项数组
   * @param merge false=全量替换，true=按 id 增量更新+追加新项
   */
  write(todos: TodoItem[], merge = false): TodoItem[] {
    if (!merge) {
      this.items = todos.map(t => this.validate(t));
    } else {
      for (const todo of todos) {
        const validated = this.validate(todo);
        const existing = this.items.find(i => i.id === validated.id);
        if (existing) {
          Object.assign(existing, validated);
        } else {
          this.items.push(validated);
        }
      }
    }
    return this.read();
  }

  read(): TodoItem[] {
    return JSON.parse(JSON.stringify(this.items));
  }

  hasItems(): boolean {
    return this.items.length > 0;
  }

  getSummary(): TodoSummary {
    const s: TodoSummary = { total: 0, pending: 0, in_progress: 0, completed: 0, cancelled: 0 };
    for (const item of this.items) {
      s.total++;
      s[item.status]++;
    }
    return s;
  }

  /** 上下文压缩后注入，只保留 pending + in_progress */
  formatForInjection(): string | null {
    const active = this.items.filter(i => i.status === 'pending' || i.status === 'in_progress');
    if (active.length === 0) return null;
    const lines = active.map(i => {
      const marker = i.status === 'in_progress' ? '[>]' : '[ ]';
      return `- ${marker} ${i.id}. ${i.content} (${i.status})`;
    });
    return '[你的活跃任务列表在上下文压缩后被保留]\n' + lines.join('\n');
  }

  /** 从历史消息中恢复 todo 状态 */
  static hydrateFromHistory(messages: any[]): TodoStore {
    const store = new TodoStore();
    for (let i = messages.length - 1; i >= 0; i--) {
      const msg = messages[i];
      if (msg.role === 'tool' && msg.toolName === 'todo') {
        try {
          const data = JSON.parse(typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content));
          if (data.todos) {
            store.write(data.todos, false);
          }
        } catch { /* 忽略解析失败 */ }
        break;
      }
    }
    return store;
  }

  private validate(item: Partial<TodoItem>): TodoItem {
    return {
      id: item.id || '?',
      content: item.content || '(无描述)',
      status: VALID_STATUSES.includes(item.status!) ? item.status! as TodoItem['status'] : 'pending',
    };
  }
}
