import type { LegacyPost } from "@/lib/legacy/content";

export type Topic =
  | "Knee"
  | "Ankle & Foot"
  | "Shoulder"
  | "Elbow, Wrist & Hand"
  | "Hip"
  | "Spine & Neck"
  | "Pediatric"
  | "Trauma"
  | "Other";

export const TOPICS: Topic[] = [
  "Knee",
  "Ankle & Foot",
  "Shoulder",
  "Elbow, Wrist & Hand",
  "Hip",
  "Spine & Neck",
  "Pediatric",
  "Trauma",
  "Other",
];

type Rule = { topic: Topic; keywords: string[] };

// Order matters: more specific regions come before trauma so a "knee fracture"
// lands under Knee, not Trauma.
const RULES: Rule[] = [
  {
    topic: "Knee",
    keywords: ["knee", "patell", "meniscus", "acl", "pcl", "mcl", "lcl"],
  },
  {
    topic: "Ankle & Foot",
    keywords: [
      "ankle",
      "achilles",
      "calcaneus",
      "calcaneal",
      "lisfranc",
      "foot",
      " toe",
      "bunion",
      "flatfoot",
      "plantar",
      "charcot",
      "metatars",
      "hallux",
    ],
  },
  {
    topic: "Shoulder",
    keywords: [
      "shoulder",
      "rotator cuff",
      "clavicle",
      "acromioclavicular",
      "glenoid",
      "biceps",
      "scapula",
    ],
  },
  {
    topic: "Elbow, Wrist & Hand",
    keywords: [
      "elbow",
      "wrist",
      " hand",
      "carpal",
      "cubital",
      "epicondyl",
      "dupuytren",
      "trigger finger",
      "tennis",
      "golfer",
      "ulnar",
    ],
  },
  {
    topic: "Hip",
    keywords: [
      "hip",
      "femur",
      "femoral",
      "acetabul",
      "scfe",
      "trochant",
      "piriformis",
    ],
  },
  {
    topic: "Spine & Neck",
    keywords: [
      "spine",
      " back",
      " neck",
      "cervic",
      "lumbar",
      " disc",
      "scoliosis",
      "stenosis",
      "corpectomy",
      "laminectomy",
      "kyphosis",
      "spondy",
      "myelopathy",
    ],
  },
  {
    topic: "Pediatric",
    keywords: ["adolescent", "pediatric", "paediatric", "child"],
  },
  {
    topic: "Trauma",
    keywords: ["fracture", "dislocat", "trauma", "injury", "sprain"],
  },
];

export function topicFor(post: Pick<LegacyPost, "title" | "excerpt">): Topic {
  const hay = `${post.title} ${post.excerpt}`.toLowerCase();
  for (const rule of RULES) {
    if (rule.keywords.some((k) => hay.includes(k))) return rule.topic;
  }
  return "Other";
}

export function countByTopic(posts: LegacyPost[]): Record<Topic, number> {
  const out = Object.fromEntries(TOPICS.map((t) => [t, 0])) as Record<
    Topic,
    number
  >;
  for (const p of posts) out[topicFor(p)] += 1;
  return out;
}
