import i18n from 'i18next';

import type { UserProfileV1_2 } from '../features/userProfileScoring';
import { toBackendLocaleFromLanguageTag } from '../i18n/locale';
import { httpJson } from '../utils/http';

export type RecommendedItem = {
  content_id: number;
  text: string;
  final_score: number;
  fallback_level_final: number;
  explanations?: Record<string, unknown> | null;
};

export type RecoMeta = Record<string, unknown>;

export type RecoEngineResult = {
  items: RecommendedItem[];
  meta: RecoMeta;
};

export type RecoRequest = {
  k?: number;
  user_profile: UserProfileV1_2;
  already_recommended_ids?: Array<string | number>;
  touched_or_viewed_ids?: Array<string | number>;
  now?: string; // ISO8601（可选）
};

export async function fetchRecoFeed(req: RecoRequest): Promise<RecoEngineResult> {
  const acceptLanguage = toBackendLocaleFromLanguageTag(i18n.language);

  const headers: Record<string, string> = {
    // 让后端做 locale 选择（目前后端只区分 en/tc）
    'Accept-Language': acceptLanguage,
  };
  const bodyObj = {
    k: req.k,
    user_profile: req.user_profile,
    already_recommended_ids: req.already_recommended_ids ?? [],
    touched_or_viewed_ids: req.touched_or_viewed_ids ?? [],
    now: req.now,
  };

  return await httpJson<RecoEngineResult>({
    path: '/v1/reco/feed',
    method: 'POST',
    headers,
    body: bodyObj,
    timeoutMs: 12_000,
    debugLabel: 'Feed API',
  });
}

export async function fetchRecoWidget(req: RecoRequest): Promise<RecoEngineResult> {
  const acceptLanguage = toBackendLocaleFromLanguageTag(i18n.language);

  const headers: Record<string, string> = {
    // 让后端做 locale 选择（目前后端只区分 en/tc）
    'Accept-Language': acceptLanguage,
  };

  const bodyObj = {
    k: req.k ?? 1,
    user_profile: req.user_profile,
    already_recommended_ids: req.already_recommended_ids ?? [],
    touched_or_viewed_ids: req.touched_or_viewed_ids ?? [],
    now: req.now,
  };

  return await httpJson<RecoEngineResult>({
    path: '/v1/reco/widget',
    method: 'POST',
    headers,
    body: bodyObj,
    timeoutMs: 12_000,
    debugLabel: 'Widget API',
  });
}

