import { isOnTopicTag } from "@/lib/topic-anchor";
import type { ResearchMap, SuggestedTag } from "@/lib/types/research";

export interface PreserveTagsInput {
  label: string;
  query: string;
  brief?: string | null;
}

/** 已勾選的標籤即使 AI 新產出沒有，也保留在清單與勾選狀態。 */
export function reconcileSelectedTags(
  previousSelected: string[],
  map: ResearchMap,
  input: PreserveTagsInput
): { researchMap: ResearchMap; selectedTags: string[] } {
  if (previousSelected.length === 0) {
    return { researchMap: map, selectedTags: [] };
  }

  const suggested = new Set(map.suggestedTags.map((t) => t.tag));
  const extras: SuggestedTag[] = [];
  const keptSelected: string[] = [];

  for (const tag of previousSelected) {
    const clean = tag.replace(/^@/, "").trim();
    if (!clean) continue;
    if (!isOnTopicTag(clean, input, { allowBroad: true })) continue;

    keptSelected.push(tag);
    if (!suggested.has(tag)) {
      extras.push({
        tag,
        reason: "使用者已勾選保留",
        searchIntent: tag.startsWith("@") ? "經驗" : "知識",
        searchType: tag.startsWith("@") ? "帳號" : clean.length <= 4 ? "短詞" : "情境",
      });
      suggested.add(tag);
    }
  }

  return {
    researchMap:
      extras.length > 0
        ? { ...map, suggestedTags: [...map.suggestedTags, ...extras] }
        : map,
    selectedTags: keptSelected,
  };
}