import { describe, expect, it } from 'vitest';

import {
  buildUserProfileFromQuestionnaire,
  computeProfileConfidence,
  computeTimeConfidence,
  normalizeAnswers,
} from '../index';

describe('userProfileScoring V1.2', () => {
  it('normalizeAnswers: 非法值按跳过处理', () => {
    // @ts-expect-error: 模拟非法输入
    const out = normalizeAnswers({ mom_stage: 'xxx', emotion: 'yyy', context: 'zzz', need: 'ooo' });
    expect(out).toEqual({ mom_stage: undefined, emotion: undefined, context: undefined, need: undefined });
  });

  it('computeTimeConfidence: 分段衰减', () => {
    const gen = new Date('2026-01-01T00:00:00Z');

    // 0–7 天：1.0
    expect(computeTimeConfidence(gen, new Date('2026-01-05T00:00:00Z'))).toBe(1.0);

    // 30 天以上：0.5
    expect(computeTimeConfidence(gen, new Date('2026-02-15T00:00:00Z'))).toBe(0.5);
  });

  it('computeProfileConfidence: 完整度因子 + clamp', () => {
    const confTime = 1.0;

    // 全部跳过：completion=0 → completionFactor=0.5 → 0.5
    expect(
      computeProfileConfidence(confTime, { stage: false, emotion: false, context: false, need: false })
    ).toBe(0.5);

    // 全部作答：completion=1 → completionFactor=1 → 1
    expect(computeProfileConfidence(confTime, { stage: true, emotion: true, context: true, need: true })).toBe(1.0);
  });

  it('buildUserProfileFromQuestionnaire: 全部跳过输出最小可计算画像', () => {
    const p = buildUserProfileFromQuestionnaire({}, { generatedAt: '2026-01-30T00:00:00Z', now: '2026-01-30T00:00:00Z' });

    expect(p.profile_version).toBe('v1.2');
    expect(p.profile_source).toBe('questionnaire');

    expect(p.profile_answered).toEqual({ stage: false, emotion: false, context: false, need: false });
    expect(p.stage).toEqual({ unknown: 1 });
    expect(p.emotion_score).toBeNull();
    expect(p.context).toEqual({});
    expect(p.need).toEqual({});

    // conf_time=1，completionFactor=0.5
    expect(p.profile_confidence).toBe(0.5);

    // unknown 会命中 unsafe_for_stage_unknown，并带跨维度谓词
    expect(p.hard_rules.forbidden_risk_flags).toContain('unsafe_for_stage_unknown');
    expect(p.hard_rules.forbidden_content_predicates.some((x) => x.id === 'unknown_block_parenting_pressure_personalized')).toBe(
      true
    );
  });

  it('buildUserProfileFromQuestionnaire: emotion<=0.2 命中 unsafe_for_emotion_low', () => {
    const p = buildUserProfileFromQuestionnaire(
      { mom_stage: 'expecting', emotion: 'overwhelmed', context: 'health', need: 'anxiety_relief' },
      { generatedAt: '2026-01-30T00:00:00Z', now: '2026-01-30T00:00:00Z' }
    );
    expect(p.emotion_score).toBe(0.2);
    expect(p.hard_rules.forbidden_risk_flags).toContain('unsafe_for_emotion_low');
  });
});

