All files / web/src/lib/tasks session-song.ts

0% Statements 0/916
0% Branches 0/1
0% Functions 0/1
0% Lines 0/916

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Session Song background task handler.
 *
 * Orchestrates the song generation pipeline:
 * 1. Check idempotency (existing song for this session plan)
 * 2. Create session_songs record
 * 3. Extract session stats
 * 4. Generate LLM composition plan (structured lyrics + style)
 * 5. Generate music via ElevenLabs Music API
 * 6. Save MP3 locally, mark completed, emit Socket.IO event
 */

import { and, desc, eq, sql } from 'drizzle-orm'
import { mkdir, writeFile } from 'fs/promises'
import { dirname, join } from 'path'
import { db, schema } from '@/db'
import type { PlayerSessionPreferencesConfig } from '@/db/schema/player-session-preferences'
import type {
  SessionSong,
  SessionSongLLMOutput,
  SessionSongTriggerSource,
} from '@/db/schema/session-songs'
import { AiFeature } from '@/lib/ai-usage/features'
import { recordElevenLabsUsage } from '@/lib/ai-usage/helpers'
import { getFlag } from '@/lib/feature-flags'
import { getSocketIO } from '@/lib/socket-io'
import {
  type CompositionPlan,
  generateMusic,
  type MusicAlignmentJson,
} from '../elevenlabs/music-client'
import { classifySongFailure } from '../session-song/classify-failure'
import {
  resolveSongPlanValidationPolicy,
  SESSION_SONG_PLAN_VALIDATION_FLAG,
  SongCompositionValidationError,
  type SongPlanValidationPolicy,
} from '../session-song/composition-plan-validation'
import { resolveSongGenres, selectSongConcept } from '../session-song/concept-selector'
import { extractSessionStats, type SongPromptInput } from '../session-song/extract-session-stats'
import { generateSongPrompt, type SongCompositionOutput } from '../session-song/prompt-generator'
import { createTask, type TaskHandle } from '../task-manager'
import type { SessionSongEvent } from './events'

// ============================================================================
// Types
// ============================================================================

export interface SessionSongInput {
  sessionPlanId: string
  playerId: string
  triggerSource: SessionSongTriggerSource
  _userId?: string
}

export interface SessionSongOutput {
  songId: string
  status: string
}

export type SessionSongRegenerationMode = 'auto' | 'reuse_prompt' | 'regenerate_prompt'

interface SongPromptBuildResult {
  playerName: string
  disabled: boolean
  promptInput?: SongPromptInput
  genrePreference?: string
}

const SONGS_DIR = join(process.cwd(), 'data', 'audio', 'songs')

/**
 * Write the ElevenLabs word-alignment JSON to a sidecar file next to the MP3.
 * The detailed music endpoint returns this when `with_timestamps: true` is set;
 * it powers karaoke-style lyric highlighting in the celebration UI.
 */
async function writeAlignmentSidecar(
  songId: string,
  alignment: MusicAlignmentJson | null
): Promise<void> {
  if (!alignment) return
  const alignmentPath = join(SONGS_DIR, `${songId}.json`)
  await writeFile(alignmentPath, JSON.stringify(alignment))
}

function asRecord(value: unknown): Record<string, unknown> | null {
  return value && typeof value === 'object' && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null
}

function nestedRecord(value: unknown, key: string): Record<string, unknown> | null {
  return asRecord(asRecord(value)?.[key])
}

function stringArray(value: unknown): string[] {
  return Array.isArray(value)
    ? value.filter((item): item is string => typeof item === 'string')
    : []
}

function getRecentSongConceptIds(
  songs: Array<{ promptInput: unknown; llmOutput: unknown }>
): string[] {
  return songs
    .map((song) => {
      const promptConcept = nestedRecord(song.promptInput, 'songConcept')
      const outputConcept = nestedRecord(song.llmOutput, 'songConcept')
      return promptConcept?.id ?? outputConcept?.id
    })
    .filter((id): id is string => typeof id === 'string' && id.length > 0)
}

function getRecentSongGenreTags(songs: Array<{ llmOutput: unknown }>): string[] {
  return songs.flatMap((song) => {
    const plan = nestedRecord(song.llmOutput, 'plan')
    return stringArray(plan?.positive_global_styles)
  })
}

function seedPart(value: unknown): string {
  if (value instanceof Date) return String(value.getTime())
  if (value == null) return ''
  return String(value)
}

function buildConceptSeed(
  input: SessionSongInput,
  plan: { createdAt?: unknown; completedAt?: unknown }
) {
  return [input.playerId, input.sessionPlanId, seedPart(plan.completedAt), seedPart(plan.createdAt)]
    .filter(Boolean)
    .join(':')
}

async function getSongPlanValidationPolicy(userId?: string): Promise<SongPlanValidationPolicy> {
  try {
    const flag = await getFlag(SESSION_SONG_PLAN_VALIDATION_FLAG, userId ? { userId } : undefined)
    return resolveSongPlanValidationPolicy(flag)
  } catch (error) {
    console.error('[session-song] Failed to load plan-validation feature flag:', error)
    return resolveSongPlanValidationPolicy(null)
  }
}

function getCompositionPlan(llmOutput: unknown): CompositionPlan | null {
  const output = asRecord(llmOutput)
  const plan = asRecord(output?.plan)
  if (!plan) return null

  if (!Array.isArray(plan.positive_global_styles)) return null
  if (!Array.isArray(plan.negative_global_styles)) return null
  if (!Array.isArray(plan.sections)) return null

  return plan as unknown as CompositionPlan
}

function getSongTitle(llmOutput: unknown): string | null {
  const title = asRecord(llmOutput)?.title
  return typeof title === 'string' ? title : null
}

async function getPlayerName(playerId: string): Promise<string> {
  const [player] = await db
    .select({ name: schema.players.name })
    .from(schema.players)
    .where(eq(schema.players.id, playerId))
    .limit(1)

  return player?.name ?? 'Unknown player'
}

async function buildSongPromptInput(input: SessionSongInput): Promise<SongPromptBuildResult> {
  const [plan] = await db
    .select()
    .from(schema.sessionPlans)
    .where(eq(schema.sessionPlans.id, input.sessionPlanId))
    .limit(1)

  const [player] = await db
    .select()
    .from(schema.players)
    .where(eq(schema.players.id, input.playerId))
    .limit(1)

  if (!plan || !player) {
    throw new Error('Session plan or player not found')
  }

  const [prefRow] = await db
    .select()
    .from(schema.playerSessionPreferences)
    .where(eq(schema.playerSessionPreferences.playerId, input.playerId))
    .limit(1)

  const prefs = prefRow ? (JSON.parse(prefRow.config) as PlayerSessionPreferencesConfig) : null
  const studentSongEnabled = prefs?.sessionSongEnabled ?? true
  if (!studentSongEnabled) {
    return { playerName: player.name, disabled: true }
  }

  const rawGenre = prefs?.sessionSongGenre ?? 'shuffle'

  const recentPlans = await db
    .select()
    .from(schema.sessionPlans)
    .where(
      and(
        eq(schema.sessionPlans.playerId, input.playerId),
        eq(schema.sessionPlans.status, 'completed')
      )
    )
    .orderBy(schema.sessionPlans.createdAt)
    .limit(10)

  const recentSessions = recentPlans.map((p) => {
    const results = (p as { results: Array<{ isCorrect: boolean }> }).results ?? []
    const correct = results.filter((r) => r.isCorrect).length
    return {
      accuracy: results.length > 0 ? correct / results.length : 0,
    }
  })

  const recentSongs = await db
    .select({
      promptInput: schema.sessionSongs.promptInput,
      llmOutput: schema.sessionSongs.llmOutput,
    })
    .from(schema.sessionSongs)
    .where(
      and(
        eq(schema.sessionSongs.playerId, input.playerId),
        eq(schema.sessionSongs.status, 'completed')
      )
    )
    .orderBy(desc(schema.sessionSongs.createdAt))
    .limit(10)

  const [gameBreakResult] = await db
    .select()
    .from(schema.gameResults)
    .where(
      and(
        eq(schema.gameResults.sessionId, input.sessionPlanId),
        eq(schema.gameResults.sessionType, 'practice-break')
      )
    )
    .limit(1)

  const stats = extractSessionStats(plan as never, player, recentSessions, gameBreakResult, {
    breakSelectedGame: plan.breakSelectedGame ?? null,
    breakReason: plan.breakReason ?? null,
    breakResults: plan.breakResults ?? null,
  })
  const conceptContext = {
    seed: buildConceptSeed(input, plan),
    recentConceptIds: getRecentSongConceptIds(recentSongs),
    recentGenreTags: getRecentSongGenreTags(recentSongs),
    genrePreference: rawGenre,
  }
  const songConcept = selectSongConcept(stats, conceptContext)
  const genrePreference = resolveSongGenres(rawGenre, songConcept, conceptContext)

  return {
    playerName: player.name,
    disabled: false,
    promptInput: { ...stats, songConcept },
    genrePreference,
  }
}

async function emitSongReady(input: SessionSongInput, songId: string) {
  try {
    const io = await getSocketIO()
    if (io) {
      io.emit(`session-song:ready:${input.sessionPlanId}`, {
        songId,
        planId: input.sessionPlanId,
      })
    }
  } catch {
    // Socket.IO not available — client will pick up via polling
  }
}

async function generateAndSaveMusic({
  songId,
  input,
  handle,
  llmOutput,
  markContentResolved = false,
}: {
  songId: string
  input: SessionSongInput
  handle: TaskHandle<SessionSongOutput, SessionSongEvent>
  llmOutput: SongCompositionOutput | Pick<SessionSongLLMOutput, 'title' | 'plan'>
  markContentResolved?: boolean
}) {
  handle.emit({ type: 'song_generating_music' })
  handle.setProgress(60, 'Creating your music...')

  await db
    .update(schema.sessionSongs)
    .set({
      status: 'generating',
      errorMessage: null,
      failureKind: null,
    })
    .where(eq(schema.sessionSongs.id, songId))

  const { audioBuffer, alignment } = await generateMusic({
    compositionPlan: llmOutput.plan,
  })

  if (input._userId) {
    recordElevenLabsUsage(llmOutput.plan, {
      userId: input._userId,
      feature: AiFeature.MUSIC_GENERATE,
      backgroundTaskId: handle.id,
    })
  }

  handle.setProgress(90, 'Saving your song...')

  const localPath = join(SONGS_DIR, `${songId}.mp3`)
  await mkdir(dirname(localPath), { recursive: true })
  await writeFile(localPath, audioBuffer)
  await writeAlignmentSidecar(songId, alignment)

  await db
    .update(schema.sessionSongs)
    .set({
      status: 'completed',
      localFilePath: localPath,
      completedAt: new Date(),
      errorMessage: null,
      failureKind: null,
      ...(markContentResolved ? { contentReviewStatus: 'resolved' } : {}),
    })
    .where(eq(schema.sessionSongs.id, songId))

  await emitSongReady(input, songId)

  handle.complete({ songId, status: 'completed' })
}

async function notifyAdminsOfSongFailure({
  songId,
  input,
  playerName,
  failureKind,
}: {
  songId: string
  input: SessionSongInput
  playerName: string
  failureKind: string
}) {
  try {
    const admins = await db
      .select({ id: schema.users.id })
      .from(schema.users)
      .where(eq(schema.users.role, 'admin'))

    if (admins.length === 0) return

    const [{ bootstrapChannels }, { notifyUser }] = await Promise.all([
      import('@/lib/notifications/bootstrap'),
      import('@/lib/notifications/dispatcher'),
    ])

    bootstrapChannels()

    const event = {
      type: 'admin-song-failed' as const,
      data: {
        songId,
        sessionPlanId: input.sessionPlanId,
        playerId: input.playerId,
        playerName,
        failureKind,
        adminUrl: '/admin/songs',
      },
    }

    const results = await Promise.allSettled(admins.map((admin) => notifyUser(admin.id, event)))
    const failures = results.filter((result) => result.status === 'rejected')
    if (failures.length > 0) {
      console.error(
        `[session-song] Failed to notify ${failures.length} admin(s) about song failure`
      )
    }
  } catch (error) {
    console.error('[session-song] Failed to notify admins about song failure:', error)
  }
}

// ============================================================================
// Handler
// ============================================================================

/**
 * Start a session song generation background task.
 *
 * Idempotent — returns existing song if one already exists for this plan.
 *
 * @returns The background task ID
 */
export async function startSessionSongGeneration(
  input: SessionSongInput,
  userId?: string
): Promise<{ taskId: string; songId?: string; existing?: boolean }> {
  // Check for existing song (idempotency)
  const existing = await db
    .select()
    .from(schema.sessionSongs)
    .where(eq(schema.sessionSongs.sessionPlanId, input.sessionPlanId))
    .limit(1)

  if (existing.length > 0) {
    return {
      taskId: existing[0].backgroundTaskId ?? '',
      songId: existing[0].id,
      existing: true,
    }
  }

  // Create the song record first so we can reference its ID
  const [songRecord] = await db
    .insert(schema.sessionSongs)
    .values({
      sessionPlanId: input.sessionPlanId,
      playerId: input.playerId,
      triggerSource: input.triggerSource,
      status: 'pending',
    })
    .returning()

  const songId = songRecord.id

  const inputWithUser = { ...input, _userId: userId }
  const taskId = await createTask<SessionSongInput, SessionSongOutput, SessionSongEvent>(
    'session-song',
    inputWithUser,
    async (handle) => {
      let playerNameForFailure = 'Unknown player'

      try {
        // Step 1: Extract stats
        handle.emit({ type: 'song_extracting_stats' })
        handle.setProgress(10, 'Analyzing session data...')

        const [plan] = await db
          .select()
          .from(schema.sessionPlans)
          .where(eq(schema.sessionPlans.id, input.sessionPlanId))
          .limit(1)

        const [player] = await db
          .select()
          .from(schema.players)
          .where(eq(schema.players.id, input.playerId))
          .limit(1)

        if (!plan || !player) {
          throw new Error('Session plan or player not found')
        }
        playerNameForFailure = player.name

        // Check per-student preference
        const [prefRow] = await db
          .select()
          .from(schema.playerSessionPreferences)
          .where(eq(schema.playerSessionPreferences.playerId, input.playerId))
          .limit(1)

        const prefs = prefRow
          ? (JSON.parse(prefRow.config) as PlayerSessionPreferencesConfig)
          : null
        const studentSongEnabled = prefs?.sessionSongEnabled ?? true
        if (!studentSongEnabled) {
          // Student has songs disabled — complete silently
          handle.complete({ songId, status: 'disabled' })
          await db
            .update(schema.sessionSongs)
            .set({ status: 'failed', errorMessage: 'Songs disabled for this student' })
            .where(eq(schema.sessionSongs.id, songId))
          return
        }

        const rawGenre = prefs?.sessionSongGenre ?? 'shuffle'

        // Get recent completed sessions for history
        const recentPlans = await db
          .select()
          .from(schema.sessionPlans)
          .where(
            and(
              eq(schema.sessionPlans.playerId, input.playerId),
              eq(schema.sessionPlans.status, 'completed')
            )
          )
          .orderBy(schema.sessionPlans.createdAt)
          .limit(10)

        const recentSessions = recentPlans.map((p) => {
          const results = (p as { results: Array<{ isCorrect: boolean }> }).results ?? []
          const correct = results.filter((r) => r.isCorrect).length
          return {
            accuracy: results.length > 0 ? correct / results.length : 0,
          }
        })

        const recentSongs = await db
          .select({
            promptInput: schema.sessionSongs.promptInput,
            llmOutput: schema.sessionSongs.llmOutput,
          })
          .from(schema.sessionSongs)
          .where(
            and(
              eq(schema.sessionSongs.playerId, input.playerId),
              eq(schema.sessionSongs.status, 'completed')
            )
          )
          .orderBy(desc(schema.sessionSongs.createdAt))
          .limit(10)

        // Look up game break result for this session (if any).
        // The smart trigger only fires in the last practice part, so game break
        // results (which happen between parts) are already persisted by now.
        const [gameBreakResult] = await db
          .select()
          .from(schema.gameResults)
          .where(
            and(
              eq(schema.gameResults.sessionId, input.sessionPlanId),
              eq(schema.gameResults.sessionType, 'practice-break')
            )
          )
          .limit(1)

        const stats = extractSessionStats(plan as never, player, recentSessions, gameBreakResult, {
          breakSelectedGame: plan.breakSelectedGame ?? null,
          breakReason: plan.breakReason ?? null,
          breakResults: plan.breakResults ?? null,
        })
        const conceptContext = {
          seed: buildConceptSeed(input, plan),
          recentConceptIds: getRecentSongConceptIds(recentSongs),
          recentGenreTags: getRecentSongGenreTags(recentSongs),
          genrePreference: rawGenre,
        }
        const songConcept = selectSongConcept(stats, conceptContext)
        const genrePreference = resolveSongGenres(rawGenre, songConcept, conceptContext)
        const promptInput = { ...stats, songConcept }

        // Update song record with prompt input
        await db
          .update(schema.sessionSongs)
          .set({
            promptInput: promptInput as unknown as Record<string, unknown>,
            status: 'prompt_generating',
          })
          .where(eq(schema.sessionSongs.id, songId))

        // Step 2: Generate LLM composition plan
        handle.emit({ type: 'song_generating_prompt' })
        handle.setProgress(30, 'Writing your song...')

        const validationPolicy = await getSongPlanValidationPolicy(input._userId)
        const llmOutput = await generateSongPrompt(promptInput, genrePreference, input._userId, {
          validationPolicy,
        })

        handle.emit({
          type: 'song_prompt_ready',
          title: llmOutput.title,
        })
        handle.setProgress(50, 'Song lyrics ready!')

        // Update song record with LLM output
        await db
          .update(schema.sessionSongs)
          .set({
            llmOutput: llmOutput as unknown as Record<string, unknown>,
          })
          .where(eq(schema.sessionSongs.id, songId))

        // Step 3: Generate music via ElevenLabs
        handle.emit({ type: 'song_generating_music' })
        handle.setProgress(60, 'Creating your music...')

        await db
          .update(schema.sessionSongs)
          .set({ status: 'generating' })
          .where(eq(schema.sessionSongs.id, songId))

        const { audioBuffer, alignment } = await generateMusic({
          compositionPlan: llmOutput.plan,
        })

        if (input._userId) {
          recordElevenLabsUsage(llmOutput.plan, {
            userId: input._userId,
            feature: AiFeature.MUSIC_GENERATE,
            backgroundTaskId: handle.id,
          })
        }

        // Step 4: Save MP3 (and alignment JSON sidecar) locally
        handle.setProgress(90, 'Saving your song...')

        const localPath = join(SONGS_DIR, `${songId}.mp3`)
        await mkdir(dirname(localPath), { recursive: true })
        await writeFile(localPath, audioBuffer)
        await writeAlignmentSidecar(songId, alignment)

        // Step 5: Mark completed
        await db
          .update(schema.sessionSongs)
          .set({
            status: 'completed',
            localFilePath: localPath,
            completedAt: new Date(),
          })
          .where(eq(schema.sessionSongs.id, songId))

        // Emit Socket.IO event for instant client notification
        try {
          const io = await getSocketIO()
          if (io) {
            io.emit(`session-song:ready:${input.sessionPlanId}`, {
              songId,
              planId: input.sessionPlanId,
            })
          }
        } catch {
          // Socket.IO not available — client will pick up via polling
        }

        handle.complete({ songId, status: 'completed' })
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Unknown error'
        const classified = classifySongFailure(error)
        const blockedOutput =
          error instanceof SongCompositionValidationError && error.candidate
            ? {
                title: error.candidate.title,
                plan: {
                  positive_global_styles: error.candidate.positive_global_styles,
                  negative_global_styles: error.candidate.negative_global_styles,
                  sections: error.candidate.sections,
                },
                validation: error.metadata,
              }
            : null

        handle.emit({ type: 'song_error', error: message })

        // Update song record with error + classification
        await db
          .update(schema.sessionSongs)
          .set({
            status: 'failed',
            errorMessage: message,
            failureKind: classified.kind,
            ...(blockedOutput && {
              llmOutput: blockedOutput as unknown as Record<string, unknown>,
            }),
          })
          .where(eq(schema.sessionSongs.id, songId))

        await notifyAdminsOfSongFailure({
          songId,
          input,
          playerName: playerNameForFailure,
          failureKind: classified.kind,
        })

        handle.fail(message)
      }
    },
    userId
  )

  // Link the background task ID to the song record
  await db
    .update(schema.sessionSongs)
    .set({ backgroundTaskId: taskId })
    .where(eq(schema.sessionSongs.id, songId))

  return { taskId, songId }
}

export interface RetrySessionSongOptions {
  mode?: SessionSongRegenerationMode
  reason?: string
  userId?: string
}

function isSongActive(status: string): boolean {
  return status === 'pending' || status === 'prompt_generating' || status === 'generating'
}

function resolveRetryMode(
  song: SessionSong,
  requestedMode: SessionSongRegenerationMode
): Exclude<SessionSongRegenerationMode, 'auto'> {
  if (requestedMode === 'auto') {
    return getCompositionPlan(song.llmOutput) ? 'reuse_prompt' : 'regenerate_prompt'
  }
  return requestedMode
}

function getValidationBlockedOutput(error: unknown) {
  if (!(error instanceof SongCompositionValidationError) || !error.candidate) {
    return null
  }

  return {
    title: error.candidate.title,
    plan: {
      positive_global_styles: error.candidate.positive_global_styles,
      negative_global_styles: error.candidate.negative_global_styles,
      sections: error.candidate.sections,
    },
    validation: error.metadata,
  }
}

/**
 * Retry or regenerate an existing song without deleting the row.
 *
 * This keeps the failed song row as the durable queue:
 * - LLM failures retain promptInput and can regenerate lyrics later.
 * - ElevenLabs failures retain llmOutput.plan and can resume at music generation.
 * - Flagged completed songs can regenerate lyrics/music after prompt fixes ship.
 */
export async function retrySessionSongGeneration(
  songId: string,
  options: RetrySessionSongOptions = {}
): Promise<{
  taskId: string
  songId: string
  mode: Exclude<SessionSongRegenerationMode, 'auto'>
}> {
  const [song] = await db
    .select()
    .from(schema.sessionSongs)
    .where(eq(schema.sessionSongs.id, songId))
    .limit(1)

  if (!song) {
    throw new Error('Song not found')
  }

  if (isSongActive(song.status)) {
    throw new Error(`Song is already ${song.status}`)
  }

  const mode = resolveRetryMode(song, options.mode ?? 'auto')
  const reusablePlan = getCompositionPlan(song.llmOutput)
  if (mode === 'reuse_prompt' && !reusablePlan) {
    throw new Error('No saved composition plan is available; regenerate lyrics instead')
  }

  const retryReason =
    options.reason ??
    (mode === 'reuse_prompt' ? 'Retry from saved composition plan' : 'Regenerate lyrics and music')
  const markContentResolved = song.contentReviewStatus === 'flagged' && mode === 'regenerate_prompt'
  const inputWithUser: SessionSongInput = {
    sessionPlanId: song.sessionPlanId,
    playerId: song.playerId,
    triggerSource: (song.triggerSource as SessionSongTriggerSource | null) ?? 'completion_fallback',
    _userId: options.userId,
  }

  await db
    .update(schema.sessionSongs)
    .set({
      status: 'pending',
      errorMessage: null,
      failureKind: null,
      backgroundTaskId: null,
      lastRegenerationReason: retryReason,
      lastRegenerationAt: new Date(),
      regenerationCount: sql`${schema.sessionSongs.regenerationCount} + 1`,
      ...(mode === 'regenerate_prompt' ? { llmOutput: null } : {}),
    })
    .where(eq(schema.sessionSongs.id, songId))

  const taskId = await createTask<SessionSongInput, SessionSongOutput, SessionSongEvent>(
    'session-song',
    inputWithUser,
    async (handle) => {
      let playerNameForFailure = await getPlayerName(song.playerId)

      try {
        if (mode === 'reuse_prompt') {
          const title = getSongTitle(song.llmOutput) ?? 'Session song'
          handle.emit({ type: 'song_prompt_ready', title })
          handle.setProgress(50, 'Song lyrics ready!')

          await generateAndSaveMusic({
            songId,
            input: inputWithUser,
            handle,
            llmOutput: { title, plan: reusablePlan! },
            markContentResolved,
          })
          return
        }

        handle.emit({ type: 'song_extracting_stats' })
        handle.setProgress(10, 'Analyzing session data...')

        const built = await buildSongPromptInput(inputWithUser)
        playerNameForFailure = built.playerName

        if (built.disabled) {
          handle.complete({ songId, status: 'disabled' })
          await db
            .update(schema.sessionSongs)
            .set({
              status: 'failed',
              errorMessage: 'Songs disabled for this student',
              failureKind: 'unknown',
            })
            .where(eq(schema.sessionSongs.id, songId))
          return
        }

        if (!built.promptInput || !built.genrePreference) {
          throw new Error('Failed to build song prompt input')
        }

        await db
          .update(schema.sessionSongs)
          .set({
            promptInput: built.promptInput as unknown as Record<string, unknown>,
            status: 'prompt_generating',
            errorMessage: null,
            failureKind: null,
          })
          .where(eq(schema.sessionSongs.id, songId))

        handle.emit({ type: 'song_generating_prompt' })
        handle.setProgress(30, 'Writing your song...')

        const validationPolicy = await getSongPlanValidationPolicy(inputWithUser._userId)
        const llmOutput = await generateSongPrompt(
          built.promptInput,
          built.genrePreference,
          inputWithUser._userId,
          { validationPolicy }
        )

        handle.emit({
          type: 'song_prompt_ready',
          title: llmOutput.title,
        })
        handle.setProgress(50, 'Song lyrics ready!')

        await db
          .update(schema.sessionSongs)
          .set({
            llmOutput: llmOutput as unknown as Record<string, unknown>,
          })
          .where(eq(schema.sessionSongs.id, songId))

        await generateAndSaveMusic({
          songId,
          input: inputWithUser,
          handle,
          llmOutput,
          markContentResolved,
        })
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Unknown error'
        const classified = classifySongFailure(error)
        const blockedOutput = getValidationBlockedOutput(error)

        handle.emit({ type: 'song_error', error: message })

        await db
          .update(schema.sessionSongs)
          .set({
            status: 'failed',
            errorMessage: message,
            failureKind: classified.kind,
            ...(blockedOutput && {
              llmOutput: blockedOutput as unknown as Record<string, unknown>,
            }),
          })
          .where(eq(schema.sessionSongs.id, songId))

        await notifyAdminsOfSongFailure({
          songId,
          input: inputWithUser,
          playerName: playerNameForFailure,
          failureKind: classified.kind,
        })

        handle.fail(message)
      }
    },
    options.userId
  )

  await db
    .update(schema.sessionSongs)
    .set({ backgroundTaskId: taskId })
    .where(eq(schema.sessionSongs.id, songId))

  return { taskId, songId, mode }
}