import { Injectable } from '@nestjs/common';
import { AiGatewayService } from '../gateway/ai-gateway.service';
import { KnowledgeImportResultSchema } from '../prompts/schemas/knowledge-import.schema';
import type { KnowledgeImportResult } from '../prompts/schemas/knowledge-import.schema';

export interface KnowledgeImportInput {
  userId: string;
  rawText: string;
  sourceName?: string;
}

@Injectable()
export class KnowledgeImportWorkflow {
  constructor(private readonly gateway: AiGatewayService) {}

  async execute(input: KnowledgeImportInput): Promise<KnowledgeImportResult> {
    const maxLength = 12000;
    const truncated = input.rawText.length > maxLength
      ? input.rawText.substring(0, maxLength) + '\n\n[...内容过长，已截断...]'
      : input.rawText;

    const userMessage = [
      `【待分析文本】`,
      input.sourceName ? `来源：${input.sourceName}` : '',
      '',
      truncated,
      '',
      `请从以上文本中提取所有知识点，严格按照 JSON Schema 输出。`,
    ].join('\n');

    const response = await this.gateway.generate({
      feature: 'knowledge-import',
      userId: input.userId,
      tier: 'cheap',
      promptKey: 'knowledge-import',
      promptVersion: '1.0.0',
      messages: [
        { role: 'user', content: userMessage },
      ],
      outputSchema: KnowledgeImportResultSchema,
    });

    return response.parsed as unknown as KnowledgeImportResult;
  }
}
