import { Injectable } from '@nestjs/common';
import type { AiCall } from '../../ai-call.interface';
import type { SafetyRule } from '../../core/safety-gate.service';
import { DraftRecallBriefSchema } from './schema';
import type { DraftRecallBriefInput, DraftRecallBriefOutput } from './input.types';
import {
  DRAFT_RECALL_BRIEF_PROMPT_VERSION,
  DRAFT_RECALL_BRIEF_SYSTEM,
  buildDraftRecallBriefPrompt,
} from './prompt';

const FORBIDDEN_PHRASES = ['一定能', '保证', '绝对', '百分百', '100%', '亲爱的'];

const safetyRules: ReadonlyArray<SafetyRule<DraftRecallBriefOutput>> = [
  {
    name: 'no_forbidden_phrases',
    severity: 'block',
    check(output) {
      const hit = FORBIDDEN_PHRASES.filter((p) => output.summary.includes(p));
      return { pass: hit.length === 0, message: hit.length > 0 ? `命中禁词: ${hit.join(',')}` : undefined };
    },
  },
];

/** LLM 失败 / safety 拒收时:用召回原因拼一句最朴素的简报。 */
function fallback(input: DraftRecallBriefInput): DraftRecallBriefOutput {
  const r = input.reasons[0];
  if (!r) return { summary: '暂无明确召回原因。' };
  const cats = r.expectedCategories.join(' / ');
  const parts = [
    r.tooth ? `${r.tooth}` : null,
    r.diagnosis,
    `${r.daysSinceText}前`,
    cats ? `未启动 ${cats}` : null,
  ].filter(Boolean);
  return { summary: `${r.subLabel}:${parts.join(' · ')}。` };
}

@Injectable()
export class DraftRecallBriefCall
  implements AiCall<DraftRecallBriefInput, DraftRecallBriefOutput>
{
  readonly kind = 'summary' as const;
  readonly callKey = 'draft_recall_brief';
  readonly promptVersion = DRAFT_RECALL_BRIEF_PROMPT_VERSION;
  readonly defaultModelId = 'qwen'; // 这类一句话摘要统一走 Qwen(qwen3.7-max)
  readonly outputSchema = DraftRecallBriefSchema;
  readonly safetyRules = safetyRules;

  buildPrompt(input: DraftRecallBriefInput) {
    return {
      system: DRAFT_RECALL_BRIEF_SYSTEM,
      prompt: buildDraftRecallBriefPrompt(input),
    };
  }

  fallback(input: DraftRecallBriefInput): DraftRecallBriefOutput {
    return fallback(input);
  }
}
