import { API_BASE_URL } from '@/src/constants/env';
import type { UserProfileV1_2, UserProfileV1_2_Extended } from '@/src/features/userProfileScoring/types';
import { toBackendLocaleFromLanguageTag } from '@/src/i18n/locale';
import { fetchRecoWidget } from '@/src/services/recoApi';
import i18n from 'i18next';
import { getUserProfileScoring } from '@/src/storage/appStorage';
import { getLocalDayKey } from '@/src/utils/date';

import {
  appGroupGetString,
  appGroupReloadAllTimelines,
  appGroupSetString,
  isAppGroupStorageAvailable,
} from '@/src/services/appGroupStorage';

/**
 * App Group 共享 key（App ↔ Widget 共通）
 */
export const WIDGET_CONFIG_KEY = 'widget.config.v1';
export const WIDGET_USER_PROFILE_KEY = 'widget.userProfile.v1_2';
export const WIDGET_DAILY_RECO_KEY = 'widget.dailyReco.v1';

export type WidgetConfigV1 = {
  schema_version: 1;
  saved_at: string; // ISO8601
  apiBaseUrl: string;
};

export type WidgetUserProfileV1_2 = {
  schema_version: 1;
  saved_at: string; // ISO8601
  user_profile: UserProfileV1_2;
};

export type WidgetDailyRecoV1 = {
  schema_version: 1;
  saved_at: string; // ISO8601
  day_key: string; // YYYY-MM-DD（用户时区）
  lang: 'en' | 'tc';
  item: null | {
    content_id: number;
    text: string;
    final_score?: number;
    fallback_level_final?: number;
  };
  meta?: Record<string, unknown>;
  source?: 'app' | 'widget';
};

function safeJsonParse<T>(raw: string | null): T | null {
  if (!raw) return null;
  try {
    return JSON.parse(raw) as T;
  } catch {
    return null;
  }
}

function pickUserProfileV1_2(scoringProfile: UserProfileV1_2_Extended): UserProfileV1_2 {
  return {
    profile_version: scoringProfile.profile_version,
    profile_source: scoringProfile.profile_source,
    profile_generated_at: scoringProfile.profile_generated_at,
    profile_confidence: scoringProfile.profile_confidence,
    profile_answered: scoringProfile.profile_answered,
    stage: scoringProfile.stage,
    emotion_score: scoringProfile.emotion_score,
    context: scoringProfile.context,
    need: scoringProfile.need,
  };
}

export async function syncWidgetConfig(): Promise<void> {
  if (!isAppGroupStorageAvailable()) return;
  const payload: WidgetConfigV1 = {
    schema_version: 1,
    saved_at: new Date().toISOString(),
    apiBaseUrl: API_BASE_URL,
  };
  await appGroupSetString(WIDGET_CONFIG_KEY, JSON.stringify(payload));
}

export async function syncWidgetUserProfileFromScoring(scoringProfile: UserProfileV1_2_Extended): Promise<void> {
  if (!isAppGroupStorageAvailable()) return;
  const payload: WidgetUserProfileV1_2 = {
    schema_version: 1,
    saved_at: new Date().toISOString(),
    user_profile: pickUserProfileV1_2(scoringProfile),
  };
  await appGroupSetString(WIDGET_USER_PROFILE_KEY, JSON.stringify(payload));
}

export async function syncWidgetUserProfileFromStorage(): Promise<void> {
  const scoringProfile = await getUserProfileScoring();
  if (!scoringProfile) return;
  await syncWidgetUserProfileFromScoring(scoringProfile);
}

export async function getWidgetDailyRecoCache(): Promise<WidgetDailyRecoV1 | null> {
  if (!isAppGroupStorageAvailable()) return null;
  const raw = await appGroupGetString(WIDGET_DAILY_RECO_KEY);
  return safeJsonParse<WidgetDailyRecoV1>(raw);
}

export async function setWidgetDailyRecoCache(cache: WidgetDailyRecoV1): Promise<void> {
  if (!isAppGroupStorageAvailable()) return;
  await appGroupSetString(WIDGET_DAILY_RECO_KEY, JSON.stringify(cache));
}

/**
 * App 前台辅助刷新（不保证准点，但能提升更新及时性与一致性）
 *
 * 规则：
 * - 若共享缓存 `day_key` 已是今天 → 不请求
 * - 若缺少用户画像 → 不请求（交给 Widget 走兜底/下次重试）
 * - 成功后写入共享缓存并触发 Widget reload（系统仍可能延迟）
 */
export async function ensureDailyWidgetRecoUpToDate(args?: {
  reason?: string;
  scoringProfile?: UserProfileV1_2_Extended | null;
}): Promise<void> {
  if (!isAppGroupStorageAvailable()) return;

  // 先确保 Widget 能拿到 baseURL（dev/pro 切换时很关键）
  await syncWidgetConfig();

  const today = getLocalDayKey(new Date());
  const cached = await getWidgetDailyRecoCache();
  if (cached?.schema_version === 1 && cached.day_key === today && cached.item?.text) return;

  const scoringProfile = args?.scoringProfile ?? (await getUserProfileScoring());
  if (!scoringProfile) return;

  // 同步画像给 Widget（保证 Widget 独立拉取也有输入）
  await syncWidgetUserProfileFromScoring(scoringProfile);

  try {
    const { items, meta } = await fetchRecoWidget({
      k: 1,
      user_profile: pickUserProfileV1_2(scoringProfile),
      already_recommended_ids: [],
      touched_or_viewed_ids: [],
    });

    const top = items?.[0];
    if (!top?.text) return;

    const lang = toBackendLocaleFromLanguageTag(i18n.language);
    await setWidgetDailyRecoCache({
      schema_version: 1,
      saved_at: new Date().toISOString(),
      day_key: today,
      // 语言策略：与后端 Accept-Language 保持一致（目前只区分 en/tc）
      lang,
      item: {
        content_id: top.content_id,
        text: top.text,
        final_score: top.final_score,
        fallback_level_final: top.fallback_level_final,
      },
      meta: meta as Record<string, unknown>,
      source: 'app',
    });

    // 触发 Widget 刷新（系统仍可能延迟）
    await appGroupReloadAllTimelines();
  } catch (e) {
    // 失败不阻塞主流程；Widget 将使用缓存或兜底文案
    if (typeof __DEV__ !== 'undefined' && __DEV__) {
      console.log('[DailyWidgetReco] App 前台刷新失败：', args?.reason ?? 'unknown', e);
    }
  }
}

