import type { KBTopic } from '../types.js';

export function sequenceTopics(topics: KBTopic[]): KBTopic[] {
  if (topics.length === 0) return [];

  const idToTopic = new Map<string, KBTopic>();
  for (const t of topics) {
    idToTopic.set(t.id, t);
  }

  // Build adjacency list: id → prerequisite ids that exist in this set
  const prereqs = new Map<string, Set<string>>();
  for (const t of topics) {
    const localPrereqs = new Set(t.prerequisiteTopics.filter(id => idToTopic.has(id)));
    prereqs.set(t.id, localPrereqs);
  }

  const visited = new Set<string>();
  const result: KBTopic[] = [];
  const onStack = new Set<string>();
  let hasCycle = false;

  function visit(id: string): void {
    if (onStack.has(id)) {
      hasCycle = true;
      return;
    }
    if (visited.has(id)) return;
    onStack.add(id);
    for (const prereqId of prereqs.get(id) ?? []) {
      visit(prereqId);
    }
    onStack.delete(id);
    visited.add(id);
    const topic = idToTopic.get(id);
    if (topic) result.push(topic);
  }

  for (const t of topics) {
    visit(t.id);
  }

  if (hasCycle) {
    // Fall back to complexity_weight ascending
    return [...topics].sort((a, b) => a.complexityWeight - b.complexityWeight);
  }

  return result;
}
