All files / web/src/app/create/worksheets generatePreview.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
// Shared logic for generating worksheet previews (used by both API route and SSR)

import { execSync } from 'child_process'
import type { WorksheetFormState } from '@/app/create/worksheets/types'
import {
  generateMasteryMixedProblems,
  generateMixedProblems,
  generateProblems,
  generateSubtractionProblems,
} from './problemGenerator'
import { getSkillById } from './skills'
import { generateTypstSource } from './typstGenerator'
import { validateProblemSpace } from './utils/validateProblemSpace'
import { validateWorksheetConfig } from './validation'

export interface PreviewResult {
  success: boolean
  pages?: string[]
  totalPages?: number
  startPage?: number
  endPage?: number
  error?: string
  details?: string
  warnings?: string[] // Added for problem space validation warnings
}

export interface SinglePageResult {
  success: boolean
  page?: string
  totalPages?: number
  error?: string
  details?: string
}

/**
 * Generate worksheet preview SVG pages
 * Can be called from API routes or Server Components
 * @param config - Worksheet configuration
 * @param startPage - Optional start page (0-indexed, inclusive). Default: 0
 * @param endPage - Optional end page (0-indexed, inclusive). Default: last page
 */
export async function generateWorksheetPreview(
  config: WorksheetFormState,
  startPage?: number,
  endPage?: number
): Promise<PreviewResult> {
  const totalProblems = (config.problemsPerPage ?? 20) * (config.pages ?? 1)
  console.log(`[PREVIEW] Starting generation: ${totalProblems} problems, pages ${config.pages}`)

  try {
    console.log('[PREVIEW] Step 1: Validating configuration...')
    // Validate configuration
    const validation = validateWorksheetConfig(config)
    if (!validation.isValid || !validation.config) {
      return {
        success: false,
        error: 'Invalid configuration',
        details: validation.errors?.join(', '),
      }
    }

    const validatedConfig = validation.config
    console.log('[PREVIEW] Step 1: ✓ Configuration valid')

    // Validate problem space for duplicate risk
    const operator = validatedConfig.operator ?? 'addition'
    const spaceValidation = validateProblemSpace(
      validatedConfig.problemsPerPage,
      validatedConfig.pages,
      validatedConfig.digitRange,
      validatedConfig.pAnyStart,
      operator
    )

    if (spaceValidation.warnings.length > 0) {
      console.log('[PREVIEW] Problem space warnings:', spaceValidation.warnings)
    }

    // Generate all problems for full preview based on operator
    const mode = config.mode ?? 'custom'

    console.log(
      `[PREVIEW] Step 2: Generating ${validatedConfig.total} problems (mode: ${mode}, operator: ${operator})...`
    )

    let problems

    // Special handling for mastery + mixed mode
    if (mode === 'mastery' && operator === 'mixed') {
      // Query both skill configs
      const addSkillId = config.currentAdditionSkillId
      const subSkillId = config.currentSubtractionSkillId

      if (!addSkillId || !subSkillId) {
        return {
          success: false,
          error: 'Mixed mastery mode requires both addition and subtraction skill IDs',
          details: `Missing skill IDs - addition: ${addSkillId || 'none'}, subtraction: ${subSkillId || 'none'}. This config may have been shared before mastery mode fields were added to the share system.`,
        }
      }

      const addSkill = getSkillById(addSkillId as any)
      const subSkill = getSkillById(subSkillId as any)

      if (!addSkill || !subSkill) {
        return {
          success: false,
          error: 'Invalid skill IDs',
          details: `Addition skill ID: ${addSkillId} (${addSkill ? 'valid' : 'invalid'}), Subtraction skill ID: ${subSkillId} (${subSkill ? 'valid' : 'invalid'})`,
        }
      }

      // Use skill-specific configs
      problems = generateMasteryMixedProblems(
        validatedConfig.total,
        {
          digitRange: addSkill.digitRange,
          pAnyStart: addSkill.regroupingConfig.pAnyStart,
          pAllStart: addSkill.regroupingConfig.pAllStart,
        },
        {
          digitRange: subSkill.digitRange,
          pAnyStart: subSkill.regroupingConfig.pAnyStart,
          pAllStart: subSkill.regroupingConfig.pAllStart,
        },
        validatedConfig.seed
      )
    } else {
      // Standard problem generation
      problems =
        operator === 'addition'
          ? generateProblems(
              validatedConfig.total,
              validatedConfig.pAnyStart,
              validatedConfig.pAllStart,
              validatedConfig.interpolate,
              validatedConfig.seed,
              validatedConfig.digitRange
            )
          : operator === 'subtraction'
            ? generateSubtractionProblems(
                validatedConfig.total,
                validatedConfig.digitRange,
                validatedConfig.pAnyStart,
                validatedConfig.pAllStart,
                validatedConfig.interpolate,
                validatedConfig.seed
              )
            : generateMixedProblems(
                validatedConfig.total,
                validatedConfig.digitRange,
                validatedConfig.pAnyStart,
                validatedConfig.pAllStart,
                validatedConfig.interpolate,
                validatedConfig.seed
              )
    }

    console.log(`[PREVIEW] Step 2: ✓ Generated ${problems.length} problems`)

    // Generate Typst sources (one per page)
    // Use placeholder URL for QR code in preview (actual URL will be generated when PDF is created)
    const previewShareUrl = validatedConfig.includeQRCode
      ? 'https://abaci.one/worksheets/shared/preview'
      : undefined
    console.log(`[PREVIEW] Step 3: Generating Typst source for ${validatedConfig.pages} pages...`)
    const startTypst = Date.now()
    const typstSources = await generateTypstSource(validatedConfig, problems, previewShareUrl)
    const typstTime = Date.now() - startTypst
    const totalPages = typstSources.length
    console.log(`[PREVIEW] Step 3: ✓ Generated ${totalPages} Typst sources in ${typstTime}ms`)

    // Determine range to compile
    const start = startPage !== undefined ? Math.max(0, startPage) : 0
    const end = endPage !== undefined ? Math.min(endPage, totalPages - 1) : totalPages - 1

    // Validate range
    if (start > end || start >= totalPages) {
      return {
        success: false,
        error: `Invalid page range: start=${start}, end=${end}, totalPages=${totalPages}`,
      }
    }

    console.log(
      `[PREVIEW] Step 4: Compiling pages ${start}-${end} (${end - start + 1} pages) to SVG...`
    )

    // Compile only requested page range to SVG
    const pages: string[] = []
    const compileStart = Date.now()
    for (let i = start; i <= end; i++) {
      const pageStart = Date.now()
      const typstSource = typstSources[i]

      // Compile to SVG via stdin/stdout
      try {
        const svgOutput = execSync('typst compile --format svg - -', {
          input: typstSource,
          encoding: 'utf8',
          maxBuffer: 10 * 1024 * 1024, // 10MB limit
        })
        const pageTime = Date.now() - pageStart
        console.log(`[PREVIEW] Step 4.${i + 1}: ✓ Page ${i} compiled in ${pageTime}ms`)
        pages.push(svgOutput)
      } catch (error) {
        console.error(`Typst compilation error (page ${i}):`, error)

        // Extract the actual Typst error message
        const stderr =
          error instanceof Error && 'stderr' in error
            ? String((error as any).stderr)
            : 'Unknown compilation error'

        return {
          success: false,
          error: `Failed to compile preview (page ${i})`,
          details: stderr,
        }
      }
    }

    const totalCompileTime = Date.now() - compileStart
    console.log(
      `[PREVIEW] Step 4: ✓ All ${pages.length} pages compiled in ${totalCompileTime}ms (avg: ${Math.round(totalCompileTime / pages.length)}ms/page)`
    )

    return {
      success: true,
      pages,
      totalPages,
      startPage: start,
      endPage: end,
      warnings: spaceValidation.warnings.length > 0 ? spaceValidation.warnings : undefined,
    }
  } catch (error) {
    console.error('Error generating preview:', error)

    const errorMessage = error instanceof Error ? error.message : String(error)

    return {
      success: false,
      error: 'Failed to generate preview',
      details: errorMessage,
    }
  }
}

/**
 * Generate a single worksheet page SVG
 * Much faster than generating all pages when you only need one
 */
export async function generateSinglePage(
  config: WorksheetFormState,
  pageNumber: number
): Promise<SinglePageResult> {
  try {
    // First, validate and get total page count
    const validation = validateWorksheetConfig(config)
    if (!validation.isValid || !validation.config) {
      return {
        success: false,
        error: 'Invalid configuration',
        details: validation.errors?.join(', '),
      }
    }

    const validatedConfig = validation.config
    const totalPages = validatedConfig.pages

    // Check if requested page is valid
    if (pageNumber < 0 || pageNumber >= totalPages) {
      return {
        success: false,
        error: `Invalid page number ${pageNumber}. Total pages: ${totalPages}`,
      }
    }

    // Generate all problems (need full set to know which problems go on which page)
    // This is unavoidable because problems are distributed across pages
    const operator = validatedConfig.operator ?? 'addition'
    const mode = config.mode ?? 'custom'

    let problems

    // Same problem generation logic as generateWorksheetPreview
    if (mode === 'mastery' && operator === 'mixed') {
      const addSkillId = config.currentAdditionSkillId
      const subSkillId = config.currentSubtractionSkillId

      if (!addSkillId || !subSkillId) {
        return {
          success: false,
          error: 'Mixed mastery mode requires both addition and subtraction skill IDs',
        }
      }

      const addSkill = getSkillById(addSkillId as any)
      const subSkill = getSkillById(subSkillId as any)

      if (!addSkill || !subSkill) {
        return {
          success: false,
          error: 'Invalid skill IDs',
        }
      }

      problems = generateMasteryMixedProblems(
        validatedConfig.total,
        {
          digitRange: addSkill.digitRange,
          pAnyStart: addSkill.regroupingConfig.pAnyStart,
          pAllStart: addSkill.regroupingConfig.pAllStart,
        },
        {
          digitRange: subSkill.digitRange,
          pAnyStart: subSkill.regroupingConfig.pAnyStart,
          pAllStart: subSkill.regroupingConfig.pAllStart,
        },
        validatedConfig.seed
      )
    } else if (operator === 'mixed') {
      problems = generateMixedProblems(
        validatedConfig.total,
        validatedConfig.digitRange,
        validatedConfig.pAnyStart,
        validatedConfig.pAllStart,
        validatedConfig.interpolate,
        validatedConfig.seed
      )
    } else if (operator === 'subtraction') {
      problems = generateSubtractionProblems(
        validatedConfig.total,
        validatedConfig.digitRange,
        validatedConfig.pAnyStart,
        validatedConfig.pAllStart,
        validatedConfig.interpolate,
        validatedConfig.seed
      )
    } else {
      // Addition
      problems = generateProblems(
        validatedConfig.total,
        validatedConfig.pAnyStart,
        validatedConfig.pAllStart,
        validatedConfig.interpolate,
        validatedConfig.seed,
        validatedConfig.digitRange
      )
    }

    // Generate Typst source for ALL pages (lightweight operation)
    // Use placeholder URL for QR code in preview
    const previewShareUrl = validatedConfig.includeQRCode
      ? 'https://abaci.one/worksheets/shared/preview'
      : undefined
    const typstSources = await generateTypstSource(validatedConfig, problems, previewShareUrl)

    // Only compile the requested page
    const typstSource = typstSources[pageNumber]

    try {
      const svgOutput = execSync('typst compile --format svg - -', {
        input: typstSource,
        encoding: 'utf8',
        maxBuffer: 10 * 1024 * 1024,
      })

      return {
        success: true,
        page: svgOutput,
        totalPages,
      }
    } catch (error) {
      console.error(`Typst compilation error (page ${pageNumber}):`, error)

      const stderr =
        error instanceof Error && 'stderr' in error
          ? String((error as any).stderr)
          : 'Unknown compilation error'

      return {
        success: false,
        error: `Failed to compile page ${pageNumber}`,
        details: stderr,
      }
    }
  } catch (error) {
    console.error('Error generating single page:', error)

    const errorMessage = error instanceof Error ? error.message : String(error)

    return {
      success: false,
      error: 'Failed to generate page',
      details: errorMessage,
    }
  }
}