import { Post } from "@/types/types";

const EXPERTISE_ALIASES: Record<string, string[]> = {
  مدل: ["مدل", "مدلینگ"],
  مدلینگ: ["مدل", "مدلینگ"],
  عکاس: ["عکاس", "عکاسی"],
  عکاسی: ["عکاس", "عکاسی"],
  آرایشگر: ["آرایشگر", "زیبایی"],
  زیبایی: ["آرایشگر", "زیبایی"],
};

function expertiseMatches(a?: string, b?: string): boolean {
  if (!a || !b) return false;
  const aliases = EXPERTISE_ALIASES[a] || [a];
  return aliases.includes(b);
}

function shuffle<T>(items: T[], seed = Date.now()): T[] {
  const copy = [...items];
  let state = seed % 2147483647 || 1;
  const random = () => {
    state = (state * 16807) % 2147483647;
    return (state - 1) / 2147483646;
  };
  for (let i = copy.length - 1; i > 0; i -= 1) {
    const j = Math.floor(random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

function interleaveWeighted<T>(primary: T[], secondary: T[]): T[] {
  if (!primary.length) return shuffle(secondary);
  if (!secondary.length) return shuffle(primary);

  const result: T[] = [];
  let primaryIdx = 0;
  let secondaryIdx = 0;
  let primaryCount = 0;

  while (primaryIdx < primary.length || secondaryIdx < secondary.length) {
    if (
      secondaryIdx < secondary.length &&
      (primaryIdx >= primary.length || primaryCount >= 3)
    ) {
      result.push(secondary[secondaryIdx]);
      secondaryIdx += 1;
      primaryCount = 0;
      continue;
    }

    if (primaryIdx < primary.length) {
      result.push(primary[primaryIdx]);
      primaryIdx += 1;
      primaryCount += 1;
    } else if (secondaryIdx < secondary.length) {
      result.push(secondary[secondaryIdx]);
      secondaryIdx += 1;
    }
  }

  return result;
}

function matchesSeedCategory(post: Post, seed: Post): boolean {
  if (seed.expertise && expertiseMatches(seed.expertise, post.expertise)) {
    return true;
  }

  if (
    seed.sub_expertise?.length &&
    post.sub_expertise?.some((item) => seed.sub_expertise?.includes(item))
  ) {
    return true;
  }

  return false;
}

/** Cold-start reels order: random, but ~72% same category as clicked post */
export function reorderColdStartFeed(posts: Post[], seed: Post): Post[] {
  const sameCategory: Post[] = [];
  const others: Post[] = [];

  posts.forEach((post) => {
    if (matchesSeedCategory(post, seed)) {
      sameCategory.push(post);
    } else {
      others.push(post);
    }
  });

  const seedKey = String(seed._id || "");
  return interleaveWeighted(
    shuffle(sameCategory, seedKey.length * 997),
    shuffle(others, seedKey.length * 499)
  );
}
