import { FactKind, FactType } from '@pac/types';
import type { ActiveFact, FeatureExtractorContext } from './feature.interface';

/**
 * 「到诊」的统一口径 —— rfm / lifecycle_stage / urgency_level 三个特征共用。
 *
 * 三处原本各自抄了一遍同样的三行(encounter + actual treatment + 挂号),口径一致纯靠自觉;
 * 现在收成一处 —— 改口径只改这里,三个标签不会各走各的(它们的 description 都印着"就诊 N 次 /
 * 末诊 N 天",对不上会被客服当场发现)。
 */
export function visitFactsOf(ctx: FeatureExtractorContext): ActiveFact[] {
  const get = (t: string) => ctx.factsByType.get(t) ?? [];
  return [
    ...get(FactType.ENCOUNTER_RECORD),
    ...get(FactType.TREATMENT_RECORD).filter((f) => f.kind === FactKind.ACTUAL),
    ...get(FactType.VISIT_REGISTRATION_RECORD),
  ];
}

export interface VisitSpan {
  /** 首诊 / 末诊时刻(无到诊记录 → null) */
  first: Date | null;
  last: Date | null;
  /** 末诊那条 fact 的 id(证据链用) */
  lastFactId: string | null;
  /** 去重就诊**天数** = 业务口径的 visit_times(同日多条治疗算一次) */
  dayCount: number;
}

export function visitSpanOf(facts: ActiveFact[]): VisitSpan {
  const days = new Set<string>();
  let first: Date | null = null;
  let last: Date | null = null;
  let lastFactId: string | null = null;
  for (const f of facts) {
    if (!f.occurredAt) continue;
    days.add(f.occurredAt.toISOString().slice(0, 10));
    if (!first || f.occurredAt < first) first = f.occurredAt;
    if (!last || f.occurredAt > last) {
      last = f.occurredAt;
      lastFactId = f.id;
    }
  }
  return { first, last, lastFactId, dayCount: days.size };
}
