/**
 * অসীম প্র্যাকটিস — endless, difficulty-adaptive quiz questions.
 * Reuses generateLessons (which already handles the DEMO/no-AI fallback), and
 * nudges the effective age band up/down based on recent accuracy.
 * Server-only.
 */
import type { AgeBand, Question } from '../types';
import { AGE_BANDS } from '../types';
import { generateLessons } from '../ai';

const ORDER: AgeBand[] = AGE_BANDS.map((b) => b.id);

/** Shift the band by delta steps, clamped. */
function shiftBand(band: AgeBand, delta: number): AgeBand {
  const i = ORDER.indexOf(band);
  const j = Math.max(0, Math.min(ORDER.length - 1, i + delta));
  return ORDER[j];
}

/**
 * @param recentAccuracy 0..1 over the last practice round (undefined on first round)
 */
export async function generatePractice(
  subjectId: string,
  band: AgeBand,
  recentAccuracy?: number,
  count = 5,
): Promise<{ questions: Question[]; effectiveBand: AgeBand }> {
  let effective = band;
  if (recentAccuracy !== undefined) {
    if (recentAccuracy >= 0.85) effective = shiftBand(band, 1); // doing great → harder
    else if (recentAccuracy <= 0.4) effective = shiftBand(band, -1); // struggling → easier
  }
  const questions = await generateLessons(subjectId, effective, count);
  return { questions, effectiveBand: effective };
}
