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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
const fastify = require('fastify')({
  bodyLimit: 25 * 1024 * 1024,
  logger: {
    level: 'info',
    transport: {
      target: 'pino-pretty',
      options: {
        translateTime: 'HH:MM:ss Z',
        ignore: 'pid,hostname',
      },
    },
  },
})

const cors = require('@fastify/cors')
const { v4: uuidv4 } = require('uuid')
const wav = require('node-wav')
const fs = require('fs').promises
const { exec } = require('child_process')
const util = require('util')
const path = require('path')

const execPromise = util.promisify(exec)

// Constants
const MODEL_ID = 'Qwen/Qwen3-ForcedAligner-0.6B'
const CLEANUP_INTERVAL = 5
const JOB_TTL_SECONDS = 300
const AVG_ALIGN_SECONDS = 30.0
const MIN_AUDIO_SECONDS = 0.3
const MAX_AUDIO_SECONDS = 180.0
const ROLLING_AVG_WINDOW = 10

// Job status enum
const JobStatus = {
  QUEUED: 'queued',
  RUNNING: 'running',
  COMPLETED: 'completed',
  FAILED: 'failed',
  ABANDONED: 'abandoned',
}

const TERMINAL_STATUSES = new Set([
  JobStatus.COMPLETED,
  JobStatus.FAILED,
  JobStatus.ABANDONED,
])

// In-memory state
const state = {
  jobs: new Map(),
  metrics: {
    totalSubmitted: 0,
    totalCompleted: 0,
    totalFailed: 0,
    totalAbandoned: 0,
    totalCancelled: 0,
    startTime: new Date(),
  },
  recentDurations: [],
  workerReady: false,
}

// Register CORS
fastify.register(cors, {
  origin: '*',
  methods: ['GET', 'POST', 'OPTIONS'],
})

// JSON schema for align request
const alignSchema = {
  body: {
    type: 'object',
    required: ['audio_base64', 'text'],
    properties: {
      audio_base64: { type: 'string' },
      text: { type: 'string' },
      language: { type: 'string', default: 'English' },
      pass_number: { type: 'integer', default: 1 },
      client_id: { type: 'string', nullable: true },
    },
  },
}

const cancelSchema = {
  params: {
    type: 'object',
    required: ['id'],
    properties: {
      id: { type: 'string' },
    },
  },
  body: {
    type: 'object',
    properties: {
      client_id: { type: 'string', nullable: true },
    },
  },
}

// Helper functions
function avgAlignS() {
  if (state.recentDurations.length === 0) {
    return AVG_ALIGN_SECONDS
  }
  const sum = state.recentDurations.reduce((a, b) => a + b, 0)
  return Math.round((sum / state.recentDurations.length) * 10) / 10
}

function cleanText(text) {
  // Curly quotes to straight
  text = text.replace(/\u2018|\u2019/g, "'")
  text = text.replace(/\u201c|\u201d/g, '"')

  // Dashes to space
  text = text.replace(/\u2014|\u2013/g, ' ')

  // Ellipsis to space
  text = text.replace(/\u2026/g, ' ')

  // Newlines to space
  text = text.replace(/[\n\r]/g, ' ')

  // Collapse whitespace
  text = text.replace(/\s+/g, ' ').trim()

  return text
}

async function validateAudio(audioBase64) {
  // Decode base64
  let raw
  try {
    raw = Buffer.from(audioBase64, 'base64')
  } catch (err) {
    throw {
      statusCode: 400,
      error: 'Invalid audio',
      error_code: 'AUDIO_DECODE_ERROR',
      detail: 'audio_base64 is not valid base64.',
    }
  }

  // Parse WAV
  let wavData
  try {
    wavData = wav.decode(raw)
  } catch (err) {
    throw {
      statusCode: 400,
      error: 'Invalid audio',
      error_code: 'AUDIO_PARSE_ERROR',
      detail: `Could not parse as WAV: ${err.message}`,
    }
  }

  const { sampleRate, channelData, bitDepth } = wavData

  // Only reject if bitDepth is explicitly reported and unsupported
  if (bitDepth !== undefined && bitDepth !== 16 && bitDepth !== 32) {
    throw {
      statusCode: 400,
      error: 'Unsupported audio format',
      error_code: 'AUDIO_FORMAT_ERROR',
      detail: `Only 16-bit PCM or 32-bit float WAV supported (got ${bitDepth}-bit).`,
    }
  }

  if (sampleRate < 8000) {
    throw {
      statusCode: 400,
      error: 'Unsupported audio format',
      error_code: 'AUDIO_RATE_ERROR',
      detail: `Sample rate too low: ${sampleRate} Hz (minimum 8000 Hz).`,
    }
  }

  const numFrames = channelData[0].length
  const duration = numFrames / sampleRate

  if (duration < MIN_AUDIO_SECONDS) {
    throw {
      statusCode: 400,
      error: 'Audio too short',
      error_code: 'AUDIO_TOO_SHORT',
      detail: `Audio is ${duration.toFixed(2)}s β€” minimum is ${MIN_AUDIO_SECONDS}s.`,
    }
  }

  if (duration > MAX_AUDIO_SECONDS) {
    throw {
      statusCode: 400,
      error: 'Audio too long',
      error_code: 'AUDIO_TOO_LONG',
      detail: `Audio is ${duration.toFixed(1)}s β€” maximum is ${MAX_AUDIO_SECONDS}s.`,
    }
  }

  // Normalize to mono 16-bit
  const normalized = await normalizeWAV(raw, wavData)

  return { normalized, duration }
}

async function normalizeWAV(raw, wavData) {
  const { sampleRate, channelData, bitDepth } = wavData

  // Already mono 16-bit β€” return as-is
  if (channelData.length === 1 && bitDepth === 16) {
    return raw
  }

  // Mix down to mono
  let monoData
  if (channelData.length > 1) {
    monoData = new Float32Array(channelData[0].length)
    for (let i = 0; i < monoData.length; i++) {
      let sum = 0
      for (let ch = 0; ch < channelData.length; ch++) sum += channelData[ch][i]
      monoData[i] = sum / channelData.length
    }
  } else {
    monoData = channelData[0]
  }

  // Encode back to WAV using node-wav (no extra dependencies needed)
  return Buffer.from(wav.encode([monoData], { sampleRate, float: false, bitDepth: 16 }))
}

function jobView(job, slim = false) {
  const base = {
    job_id: job.id,
    status: job.status,
    created_at: job.createdAt.toISOString(),
  }

  switch (job.status) {
    case JobStatus.QUEUED:
      base.queue_position = 1
      base.estimated_wait_s = avgAlignS()
      base.message = 'Queued at position 1. Poll /job/{id} every 2 s.'
      break

    case JobStatus.RUNNING:
      if (job.startedAt) {
        const elapsed = (Date.now() - job.startedAt.getTime()) / 1000
        const estimatedRemaining = Math.max(0, avgAlignS() - elapsed)

        base.started_at = job.startedAt.toISOString()
        base.elapsed_s = Math.round(elapsed * 10) / 10
        base.estimated_remaining_s = Math.round(estimatedRemaining * 10) / 10
        base.message = 'Running.'
      }
      break

    case JobStatus.COMPLETED:
      base.total_words = job.result.length
      base.language = job.request.language
      base.pass_number = job.request.pass_number
      base.model = MODEL_ID
      base.fine_tuned = false

      if (job.startedAt) {
        base.started_at = job.startedAt.toISOString()
      }
      if (job.terminalAt) {
        base.completed_at = job.terminalAt.toISOString()
      }
      if (job.startedAt && job.terminalAt) {
        const duration = (job.terminalAt - job.startedAt) / 1000
        base.duration_s = Math.round(duration * 100) / 100
      }

      if (!slim) {
        base.word_timestamps = job.result
      }
      break

    case JobStatus.FAILED:
    case JobStatus.ABANDONED:
      if (job.error) {
        base.error = job.error
      }
      if (job.terminalAt) {
        base.completed_at = job.terminalAt.toISOString()
      }
      break
  }

  return base
}

function promoteQueued() {
  // Check if any running job exists
  for (const job of state.jobs.values()) {
    if (job.status === JobStatus.RUNNING) {
      return
    }
  }

  // Find oldest queued job
  let oldestQueued = null
  let oldestId = null

  for (const [id, job] of state.jobs.entries()) {
    if (job.status === JobStatus.QUEUED) {
      if (!oldestQueued || job.createdAt < oldestQueued.createdAt) {
        oldestQueued = job
        oldestId = id
      }
    }
  }

  if (oldestQueued) {
    oldestQueued.status = JobStatus.RUNNING
    oldestQueued.startedAt = new Date()
    fastify.log.info(`Promoted queued job ${oldestId} β†’ RUNNING`)

    // Start alignment
    runAlignment(oldestId)
  }
}

async function runAlignment(jobId) {
  fastify.log.info(`[${jobId}] Starting alignment`)

  const job = state.jobs.get(jobId)
  if (!job || job.status !== JobStatus.RUNNING) return

  const tempPath = path.join('/tmp', `${jobId}.wav`)

  try {
    // Write temp file
    await fs.writeFile(tempPath, job.wavBytes)

    const start = Date.now()

    // Call Python worker
    const { stdout, stderr } = await execPromise(
      `python3 worker.py ${tempPath} "${job.request.text}" "${job.request.language}"`
    )

    const duration = (Date.now() - start) / 1000

    // Parse result
    let timestamps
    try {
      timestamps = JSON.parse(stdout)
    } catch (err) {
      throw new Error(`Failed to parse alignment result: ${err.message}`)
    }

    fastify.log.info(`[${jobId}] Done β€” ${timestamps.length} words in ${duration.toFixed(2)}s`)

    // Update job
    const currentJob = state.jobs.get(jobId)
    if (currentJob && currentJob.status === JobStatus.RUNNING) {
      currentJob.status = JobStatus.COMPLETED
      currentJob.result = timestamps
      currentJob.terminalAt = new Date()

      state.metrics.totalCompleted++
      state.recentDurations.push(duration)
      if (state.recentDurations.length > ROLLING_AVG_WINDOW) {
        state.recentDurations.shift()
      }
    }
  } catch (err) {
    fastify.log.error(`[${jobId}] Alignment failed: ${err.message}`)

    const currentJob = state.jobs.get(jobId)
    if (currentJob && currentJob.status === JobStatus.RUNNING) {
      currentJob.status = JobStatus.FAILED
      currentJob.error = err.message
      currentJob.terminalAt = new Date()
      state.metrics.totalFailed++
    }
  } finally {
    // Clean up temp file
    try {
      await fs.unlink(tempPath)
    } catch (err) {
      // Ignore cleanup errors
    }

    promoteQueued()
  }
}

// Cleanup loop
async function cleanupLoop() {
  setInterval(() => {
    const now = new Date()
    const cutoff = new Date(now - JOB_TTL_SECONDS * 1000)

    for (const [id, job] of state.jobs.entries()) {
      if (TERMINAL_STATUSES.has(job.status)) {
        if (job.terminalAt && job.terminalAt < cutoff) {
          state.jobs.delete(id)
          fastify.log.info(`Purged TTL-expired job ${id}`)
        }
      }
    }

    promoteQueued()
  }, CLEANUP_INTERVAL * 1000)
}

// Routes
fastify.get('/', async () => {
  return {
    name: 'Qwen3-ForcedAligner Service',
    version: '1.5.0',
    status: 'ready',
    model: MODEL_ID,
    endpoints: {
      'POST /align': 'Submit alignment job',
      'GET /job/{id}': 'Unified status + result [preferred]',
      'GET /job/{id}?slim=true': 'Status only β€” omits word_timestamps (use while polling)',
      'GET /result/{id}': 'Legacy result poll [compat]',
      'GET /queue/status': 'Queue availability',
      'POST /cancel/{id}': 'Explicit job cancellation',
      'GET /health': 'Service health + job counts',
      'GET /metrics': 'Aggregate metrics',
    },
  }
})

fastify.get('/health', async () => {
  const counts = {
    queued: 0,
    running: 0,
    completed: 0,
    failed: 0,
    abandoned: 0,
  }

  for (const job of state.jobs.values()) {
    counts[job.status]++
  }

  const overall = state.workerReady ? 'healthy' : 'degraded'

  return {
    status: overall,
    worker_alive: state.workerReady,
    worker_ready: state.workerReady,
    worker_restarting: false,
    model: MODEL_ID,
    shm_free_mb: null,
    shm_ok: true,
    avg_align_s: avgAlignS(),
    job_counts: counts,
    total_jobs: state.jobs.size,
  }
})

fastify.get('/metrics', async () => {
  const total =
    state.metrics.totalCompleted + state.metrics.totalFailed + state.metrics.totalAbandoned
  const successRate =
    total > 0 ? Math.round((state.metrics.totalCompleted / total) * 1000) / 1000 : null

  const uptime = (Date.now() - state.metrics.startTime) / 1000

  return {
    uptime_s: Math.round(uptime),
    total_submitted: state.metrics.totalSubmitted,
    total_completed: state.metrics.totalCompleted,
    total_failed: state.metrics.totalFailed,
    total_abandoned: state.metrics.totalAbandoned,
    total_cancelled: state.metrics.totalCancelled,
    success_rate: successRate,
    worker_restarts: 0,
    avg_align_s: avgAlignS(),
    recent_durations: state.recentDurations,
  }
})

fastify.get('/queue/status', async () => {
  let runningJobId = null
  let queuedJobId  = null
 
  for (const [id, job] of state.jobs.entries()) {
    if (job.status === JobStatus.RUNNING) runningJobId = id
    if (job.status === JobStatus.QUEUED)  queuedJobId  = id
  }
 
  const runningCount = runningJobId ? 1 : 0
  const waitingCount = queuedJobId  ? 1 : 0
 
  return {
    // NEW: integer counts the controller reads
    running:          runningCount,
    waiting:          waitingCount,
    // Existing fields kept for backwards compat
    can_submit:       runningCount === 0 && waitingCount === 0,
    slot_available:   runningCount === 0,
    queue_full:       runningCount === 1 && waitingCount === 1,
    running_job_id:   runningJobId,
    queued_job_id:    queuedJobId,
    worker_ready:     state.workerReady,
    estimated_wait_s: runningJobId ? avgAlignS() : 0,
  }
})

fastify.post('/align', { schema: alignSchema }, async (request, reply) => {
  const req = request.body

  // Set defaults
  req.language = req.language || 'English'
  req.pass_number = req.pass_number || 1

  // 1. Model check
  if (!state.workerReady) {
    return reply.code(503).send({
      error: 'Worker unavailable',
      error_code: 'WORKER_DOWN',
      detail: 'Model is still loading. Retry in a few seconds.',
    })
  }

  // 2. Text validation
  const cleanedText = cleanText(req.text)
  if (!cleanedText) {
    return reply.code(400).send({
      error: 'Invalid text',
      error_code: 'TEXT_EMPTY',
      detail: 'Text is empty after normalisation.',
    })
  }
  req.text = cleanedText

  // 3. Audio validation
  let wavNormalized, audioDuration
  try {
    const result = await validateAudio(req.audio_base64)
    wavNormalized = result.normalized
    audioDuration = result.duration
  } catch (err) {
    return reply.code(err.statusCode || 400).send(err)
  }

  const runningExists = Array.from(state.jobs.values()).some(
    (j) => j.status === JobStatus.RUNNING
  )
  const queuedExists = Array.from(state.jobs.values()).some(
    (j) => j.status === JobStatus.QUEUED
  )

  // 4. Queue full check
  if (runningExists && queuedExists) {
    const wait = avgAlignS()
    return reply.code(503).send({
      error: 'Service busy',
      error_code: 'QUEUE_FULL',
      detail: 'One job running, one already queued. Retry after current jobs finish.',
      retry_after: wait,
    })
  }

  // 5. Duplicate client check
  let duplicateWarning = null
  if (req.client_id) {
    for (const [id, job] of state.jobs.entries()) {
      if (
        job.client_id === req.client_id &&
        (job.status === JobStatus.RUNNING || job.status === JobStatus.QUEUED)
      ) {
        duplicateWarning = {
          message: 'You already have an active job.',
          existing_job_id: id,
          existing_status: job.status,
        }
        break
      }
    }
  }

  // 6. Create job
  const status = runningExists ? JobStatus.QUEUED : JobStatus.RUNNING
  const jobId = uuidv4().split('-')[0]
  const now = new Date()

  const job = {
    id: jobId,
    request: req,
    status,
    createdAt: now,
    startedAt: status === JobStatus.RUNNING ? now : null,
    terminalAt: null,
    result: null,
    error: null,
    client_id: req.client_id,
    audioDuration: Math.round(audioDuration * 100) / 100,
    wavBytes: wavNormalized,
  }

  state.jobs.set(jobId, job)
  state.metrics.totalSubmitted++

  fastify.log.info(
    `Job ${jobId} created β€” status=${status}, duration=${audioDuration.toFixed(1)}s, client=${req.client_id}`
  )

  if (status === JobStatus.RUNNING) {
    runAlignment(jobId)
  }

  const response = {
    job_id: jobId,
    status,
    queue_position: status === JobStatus.QUEUED ? 1 : 0,
    poll_url: `/job/${jobId}`,
    estimated_wait_s: status === JobStatus.RUNNING ? 0 : avgAlignS(),
    audio_duration_s: Math.round(audioDuration * 100) / 100,
    message:
      status === JobStatus.RUNNING
        ? `Job started. Poll GET /job/${jobId}.`
        : `Job queued at position 1. Poll GET /job/${jobId} every 2 s.`,
  }

  if (duplicateWarning) {
    response.duplicate_warning = duplicateWarning
  }

  return response
})

fastify.get('/job/:id', async (request) => {
  const { id } = request.params
  const slim = request.query.slim === 'true'

  const job = state.jobs.get(id)
  if (!job) {
    throw {
      statusCode: 404,
      error: 'Job not found',
      error_code: 'JOB_NOT_FOUND',
      detail: 'Job may have been purged (TTL=5 min) or never existed.',
    }
  }

  return jobView(job, slim)
})

fastify.get('/result/:id', async (request) => {
  const { id } = request.params

  const job = state.jobs.get(id)
  if (!job) {
    throw {
      statusCode: 404,
      error: 'Job not found',
      error_code: 'JOB_NOT_FOUND',
    }
  }

  return jobView(job, false)
})

fastify.post('/cancel/:id', { schema: cancelSchema }, async (request, reply) => {
  const { id } = request.params
  const { client_id } = request.body

  const job = state.jobs.get(id)
  if (!job) {
    throw {
      statusCode: 404,
      error: 'Job not found',
      error_code: 'JOB_NOT_FOUND',
    }
  }

  // Client ID check
  if (job.client_id) {
    if (!client_id || client_id !== job.client_id) {
      throw {
        statusCode: 403,
        error: 'Client ID mismatch',
        error_code: 'FORBIDDEN',
        detail: 'You are not the owner of this job.',
      }
    }
  }

  if (TERMINAL_STATUSES.has(job.status)) {
    return {
      cancelled: false,
      status: job.status,
      message: `Job was already ${job.status} β€” nothing to cancel.`,
    }
  }

  const wasRunning = job.status === JobStatus.RUNNING

  job.status = JobStatus.ABANDONED
  job.error = 'Cancelled by client'
  job.terminalAt = new Date()

  state.metrics.totalCancelled++

  fastify.log.info(`Job ${id} cancelled (${wasRunning ? 'RUNNING' : 'QUEUED'})`)

  promoteQueued()

  return {
    cancelled: true,
    job_id: id,
    restarting: false,
    message: 'Job cancelled.',
  }
})

fastify.post('/benchmark', async (request) => {
  const req = request.body

  if (!state.workerReady) {
    throw {
      statusCode: 503,
      error: 'Model not loaded yet',
    }
  }

  const cleanedText = cleanText(req.text)
  if (!cleanedText) {
    throw {
      statusCode: 400,
      error: 'Empty text',
    }
  }

  let wavNormalized, audioDuration
  try {
    const result = await validateAudio(req.audio_base64)
    wavNormalized = result.normalized
    audioDuration = result.duration
  } catch (err) {
    throw err
  }

  const wordCount = cleanedText.split(/\s+/).length

  const tempPath = path.join('/tmp', `benchmark_${uuidv4()}.wav`)

  try {
    await fs.writeFile(tempPath, wavNormalized)

    const start = Date.now()

    const { stdout } = await execPromise(
      `python3 worker.py ${tempPath} "${req.text}" "${req.language || 'English'}"`
    )

    const actualDuration = (Date.now() - start) / 1000

    const timestamps = JSON.parse(stdout)

    return {
      audio_duration_s: Math.round(audioDuration * 1000) / 1000,
      word_count: wordCount,
      actual_align_s: Math.round(actualDuration * 1000) / 1000,
      realtime_factor: Math.round((actualDuration / audioDuration) * 1000) / 1000,
      ms_per_word:
        wordCount > 0 ? Math.round((actualDuration / wordCount) * 1000 * 10) / 10 : null,
      words_aligned: timestamps.length,
      language: req.language || 'English',
      timestamp: new Date().toISOString(),
    }
  } finally {
    try {
      await fs.unlink(tempPath)
    } catch (err) {
      // Ignore cleanup errors
    }
  }
})

// Error handler
fastify.setErrorHandler((error, request, reply) => {
  fastify.log.error(error)

  if (error.statusCode) {
    reply.code(error.statusCode).send(error)
  } else {
    reply.code(500).send({
      error: 'Internal server error',
      error_code: 'INTERNAL_ERROR',
      detail: error.message,
    })
  }
})

// Start server
const start = async () => {
  try {
    // Start cleanup loop
    cleanupLoop()

    // Simulate Python worker starting
    setTimeout(() => {
      state.workerReady = true
      fastify.log.info('Python worker ready')
    }, 10000)

    await fastify.listen({ port: 7860, host: '0.0.0.0' })
    fastify.log.info('Qwen3-ForcedAligner Service v1.5.0 ready')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()