import { Injectable } from '@nestjs/common';
import { ItemsService } from '@modules/devtracker/services/items.service';
import type { AgentTool, ToolDescriptor, ToolInvocation, ToolResult } from './tool.types';

/**
 * `project_query` tool —— PR6 真后端接入。
 *
 * 后端来源：DevTracker `ItemsService.findAll({ keyword, ... })` —— 真索引项目/任务表，
 * 不再是 PR5 的 canned 数据。
 */
@Injectable()
export class ProjectQueryTool implements AgentTool {
  constructor(private readonly itemsService: ItemsService) {}

  readonly descriptor: ToolDescriptor = {
    name: 'project_query',
    description: '查询项目/任务/需求信息（DevTracker 真实数据）。可用关键词搜索。',
    inputSchema: {
      query: { type: 'string', required: true, description: '项目名/任务名关键词' },
      limit: { type: 'number', required: false, description: '返回条数上限，默认 10' },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams'] },
  };

  async invoke(inv: ToolInvocation): Promise<ToolResult> {
    const q = String(inv.input.query ?? '').trim();
    if (!q) return { ok: false, errorMessage: 'query 不能为空' };
    const pageSize = Math.min(Number(inv.input.limit ?? 10), 50);

    try {
      const result = await this.itemsService.findAll({ keyword: q, page: 1, pageSize });
      return {
        ok: true,
        output: {
          matched: result.pagination.total,
          showing: result.items.length,
          items: result.items.map((i: any) => ({
            id: i.id,
            itemType: i.itemType,
            title: i.title,
            status: i.status,
            priority: i.priority,
            ownerId: i.ownerId,
            updatedAt: i.updatedAt,
          })),
        },
      };
    } catch (err) {
      return { ok: false, errorMessage: (err as Error).message };
    }
  }
}
