import { Injectable, Logger } from '@nestjs/common';
import type { AiCall } from '../../../../ai-call.interface';
import { StandardScriptSchema } from './schema';
import type { DraftPlanScriptInput, DraftPlanScriptOutput } from '../../shared/input.types';
import { buildStandardScriptPrompt } from './prompt';
import { composeSystem } from '../../shared/skill-composer';
import { DraftPlanScriptSkillRegistry } from '../../shared/skill-registry.service';
import { SCRIPT_SAFETY_RULES } from '../../shared/safety-rules';
import { stableTemplateFallback } from '../stable/stable.call';

/**
 * StandardScriptCall —— 标准档(投入档之二)。
 *
 * 与稳健档共用脊柱(AiCallRunner)、输入(ScriptContext)、安全闸(SCRIPT_SAFETY_RULES)、
 * 兜底(stableTemplateFallback);**差异**只在策略三件:
 *   - system:composeSystem(input, skills, 'standard') → base-common + format.standard + 人群共性知识
 *     (不含稳健句位模板;skill 按 tiers 过滤)
 *   - user:buildStandardScriptPrompt → 厚输入(病历全 + 其他reason + 近期治疗)、病种只给名(去文案模板)
 *   - schema:StandardScriptSchema(同 4 字段,describe 放宽,段内 LLM 自由编排)
 *
 * callKey 仍用 'draft_plan_script'(同一逻辑调用),档位差异落 promptVersion → eval 可按版本切档对比。
 */
const STANDARD_PROMPT_VERSION = 'draft_plan_script@2026-06-06-standard-v6'; // v3: base-common 精简;v2: 4段标题不定(sectionTitles)

@Injectable()
export class StandardScriptCall implements AiCall<DraftPlanScriptInput, DraftPlanScriptOutput> {
  private readonly logger = new Logger(StandardScriptCall.name);
  readonly kind = 'script' as const;
  readonly callKey = 'draft_plan_script';
  readonly promptVersion = STANDARD_PROMPT_VERSION;
  readonly defaultModelId = 'deepseek-v4-flash';
  readonly outputSchema = StandardScriptSchema;
  readonly safetyRules = SCRIPT_SAFETY_RULES;

  constructor(private readonly skillRegistry: DraftPlanScriptSkillRegistry) {}

  buildPrompt(input: DraftPlanScriptInput) {
    const composed = composeSystem(input, this.skillRegistry.getAllSkills(), 'standard');
    if (composed.matchedSkills.length === 0) {
      this.logger.warn(
        `[standard] compose 0 个 skill 命中(scenario=${composed.context.scenario}, ` +
          `dx=${composed.context.diagnosisCodes.join(',')}, pop=${composed.context.population}) — 仅 base`,
      );
    } else {
      this.logger.debug(
        `[standard] compose skills: ${composed.matchedSkills.map((s) => s.frontmatter.name).join(', ')} ` +
          `(hash=${composed.composeHash})`,
      );
    }
    return {
      system: composed.systemPrompt,
      prompt: buildStandardScriptPrompt(input),
    };
  }

  // 标准档失败 → 回退到稳健模板(安全网,客服永远有东西可用)
  fallback(input: DraftPlanScriptInput): DraftPlanScriptOutput {
    return stableTemplateFallback(input);
  }
}
