import { Injectable, Logger } from '@nestjs/common';
import { Action, FactKind, FactStatus, FactType } from '@pac/types';
import type { FactDraft, Parser, ParserContext } from './parser.interface';
import { normalizeToothPosition } from './tooth-position.util';

/**
 * ImageParser — `image_uploaded` 解析器
 *
 * 产 1 个 `image_record`(actual),只装 metadata + 医生 finding,**不持文件本体**。
 * 影像 AI 识别结果归 agent_invocations.output,不进 fact 层。
 */
@Injectable()
export class ImageParser implements Parser {
  readonly name = Action.IMAGE_UPLOADED;
  private readonly logger = new Logger(ImageParser.name);

  parse(ctx: ParserContext): FactDraft[] {
    const c = ctx.canonicalRow;
    const externalId = String(c.externalId ?? ctx.transaction.subjectId).trim();
    if (!externalId) {
      this.logger.warn(
        `image parser: missing externalId for transaction=${ctx.transaction.id};skip`,
      );
      return [];
    }

    const uploadedAt = c.uploadedAt ? new Date(c.uploadedAt as string) : null;
    const modality = (c.modality as string | undefined) ?? null;
    const finding = (c.finding as string | undefined) ?? null;
    const toothPositions = normalizeToothPosition(c.toothPositions as string | undefined);
    const encounterExternalId = (c.encounterExternalId as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.IMAGE_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.IMAGE_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt: uploadedAt,
        title: `影像 ${modality ?? ''} ${externalId}`,
        summary: finding,
        content: {
          image_external_id: externalId,
          modality,
          tooth_positions: toothPositions,
          finding,
          encounter_external_id: encounterExternalId,
          doctor_id: c.doctorId ? String(c.doctorId) : null,
          doctor_name: (c.doctorName as string | undefined) ?? null,
        },
      },
    ];
  }
}
