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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Incremental Offcloud sync ("delta sync").
//
// Goals, in the order they matter:
//   1. NEVER re-analyze content that is already indexed and ready to play.
//      A video that reached status "ready" is skipped forever unless its bytes
//      change (size/name) or the user explicitly forces a re-scan.
//   2. Only brand-new Offcloud content is queued for the 11-layer detection.
//   3. Content deleted from Offcloud disappears from the UI and the DEOVR feed
//      immediately (availability = "missing"), and is purged after a grace
//      period so a transient API hiccup can never wipe the library.
//   4. No manual re-scan: an auto-sync loop polls Offcloud continuously.
//   5. On every cold start (Space waking from sleep/pause) a FULL sync runs, so
//      the whole library is reconciled and loaded before the user arrives.
//
// Cheapness matters because the poll interval can be as low as 1 second: each
// cycle fetches the Offcloud listing once, hashes it, and does zero database
// writes when nothing changed.

import { db } from "./db";
import { scanLibrary, type OffcloudFile } from "./offcloud";
import { ensureSchema } from "./migrate";

export type SyncMode = "delta" | "full";
export type SyncTrigger = "boot" | "auto" | "manual" | "force";

export type AutoSyncConfig = {
  /** Master switch for continuous polling. */
  enabled: boolean;
  /** Seconds between polls. 1 is allowed; 5 is the sane default. */
  intervalSeconds: number;
  /** Run a full reconcile when the server process starts. */
  fullSyncOnBoot: boolean;
  /**

   * Hours to keep a video that vanished from Offcloud before deleting its row.

   * It is hidden from the UI and feed immediately either way. 0 = never delete.

   */
  pruneAfterHours: number;
};

export type SyncResult = {
  at: string;
  mode: SyncMode;
  trigger: SyncTrigger;
  /** False when the Offcloud listing was byte-identical to the previous poll. */
  changed: boolean;
  offcloudMode: "real" | "mock";
  discovered: number;
  added: number;
  updated: number;
  requeued: number;
  skippedReady: number;
  markedMissing: number;
  restored: number;
  pruned: number;
  durationMs: number;
  error?: string;
};

export type SyncState = {
  running: boolean;
  loopArmed: boolean;
  lastSyncAt: string | null;
  lastChangeAt: string | null;
  lastResult: SyncResult | null;
  totalSyncs: number;
  consecutiveErrors: number;
  nextPollInSeconds: number | null;
  libraryFingerprint: string | null;
};

export const AUTO_SYNC_SETTING = "auto_sync_config";
const LOG = "[sync]";
const MAX_BACKOFF_SECONDS = 60;

export function getDefaultAutoSyncConfig(): AutoSyncConfig {
  return sanitizeAutoSyncConfig({
    enabled: process.env.AUTO_SYNC_ENABLED !== "false",
    intervalSeconds: Number(process.env.AUTO_SYNC_INTERVAL_SECONDS || 5),
    fullSyncOnBoot: process.env.AUTO_SYNC_FULL_ON_BOOT !== "false",
    pruneAfterHours: Number(process.env.AUTO_SYNC_PRUNE_AFTER_HOURS || 24),
  });
}

export function sanitizeAutoSyncConfig(input: Partial<AutoSyncConfig>): AutoSyncConfig {
  let interval = Number(input.intervalSeconds);
  if (!Number.isFinite(interval)) interval = 5;
  // 1s is the floor the user asked for; 3600s the ceiling.
  interval = Math.min(3600, Math.max(1, Math.round(interval)));

  let prune = Number(input.pruneAfterHours);
  if (!Number.isFinite(prune) || prune < 0) prune = 24;
  prune = Math.min(24 * 90, Math.round(prune));

  return {
    enabled: input.enabled !== false,
    intervalSeconds: interval,
    fullSyncOnBoot: input.fullSyncOnBoot !== false,
    pruneAfterHours: prune,
  };
}

// ---------------------------------------------------------------------------
// Process-wide state (survives module re-evaluation / hot reload)
// ---------------------------------------------------------------------------

type Runtime = {
  timer: ReturnType<typeof setTimeout> | null;
  config: AutoSyncConfig | null;
  running: boolean;
  started: boolean;
  lastSyncAt: string | null;
  lastChangeAt: string | null;
  lastResult: SyncResult | null;
  totalSyncs: number;
  consecutiveErrors: number;
  fingerprint: string | null;
  nextPollAt: number | null;
};

const globalRef = globalThis as unknown as { __vrmsSync?: Runtime };

function rt(): Runtime {
  if (!globalRef.__vrmsSync) {
    globalRef.__vrmsSync = {
      timer: null,
      config: null,
      running: false,
      started: false,
      lastSyncAt: null,
      lastChangeAt: null,
      lastResult: null,
      totalSyncs: 0,
      consecutiveErrors: 0,
      fingerprint: null,
      nextPollAt: null,
    };
  }
  return globalRef.__vrmsSync;
}

// ---------------------------------------------------------------------------
// Config persistence
// ---------------------------------------------------------------------------

export async function getAutoSyncConfig(): Promise<AutoSyncConfig> {
  const state = rt();
  if (state.config) return state.config;
  try {
    const row = await db.setting.findUnique({ where: { key: AUTO_SYNC_SETTING } });
    if (row?.value) {
      state.config = sanitizeAutoSyncConfig({
        ...getDefaultAutoSyncConfig(),
        ...(JSON.parse(row.value) as Partial<AutoSyncConfig>),
      });
      return state.config;
    }
  } catch {
    // DB cold — fall through to env defaults.
  }
  state.config = getDefaultAutoSyncConfig();
  return state.config;
}

export async function updateAutoSyncConfig(

  patch: Partial<AutoSyncConfig>

): Promise<AutoSyncConfig> {
  const current = await getAutoSyncConfig();
  const next = sanitizeAutoSyncConfig({ ...current, ...patch });
  rt().config = next;
  try {
    const value = JSON.stringify(next);
    await db.setting.upsert({
      where: { key: AUTO_SYNC_SETTING },
      create: { key: AUTO_SYNC_SETTING, value },
      update: { value },
    });
  } catch (err) {
    console.warn(`${LOG} could not persist auto-sync config:`, err);
  }
  scheduleNextPoll(0);
  return next;
}

// ---------------------------------------------------------------------------
// Identity helpers
// ---------------------------------------------------------------------------

/** Stable identity of a file on Offcloud. */
function contentKeyOf(file: OffcloudFile): string {
  return `${file.offcloudId}::${file.name}`;
}

/**

 * Fingerprint of the *content*, not the URL. Offcloud stream URLs rotate, so

 * including them would make every poll look like a change and re-trigger

 * analysis — exactly what we are avoiding.

 */
function contentHashOf(file: OffcloudFile): string {
  return `${file.size}|${file.duration ?? ""}`;
}

/** Fingerprint of the whole listing, used to short-circuit unchanged polls. */
function libraryFingerprint(files: OffcloudFile[]): string {
  const parts = files
    .map((f) => `${contentKeyOf(f)}#${contentHashOf(f)}`)
    .sort();
  let h1 = 0x811c9dc5;
  let h2 = 0x01000193;
  const joined = parts.join("\n");
  for (let i = 0; i < joined.length; i++) {
    const c = joined.charCodeAt(i);
    h1 = (h1 ^ c) * 0x01000193 >>> 0;
    h2 = (h2 + c * 31) >>> 0;
  }
  return `${parts.length}-${h1.toString(16)}${h2.toString(16)}`;
}

// ---------------------------------------------------------------------------
// The sync itself
// ---------------------------------------------------------------------------

/**

 * Reconcile the local index with Offcloud.

 *

 * @param mode    "delta" skips all work when the listing is unchanged.

 *                "full" always reconciles (used on boot and manual scans).

 * @param force   Re-queue detection even for videos already "ready".

 */
export async function syncOnce(options?: {

  mode?: SyncMode;

  trigger?: SyncTrigger;

  force?: boolean;

}): Promise<SyncResult> {
  const mode = options?.mode ?? "delta";
  const trigger = options?.trigger ?? "auto";
  const force = options?.force === true;
  const state = rt();
  const startedAt = Date.now();

  const base: SyncResult = {
    at: new Date().toISOString(),
    mode,
    trigger,
    changed: false,
    offcloudMode: "real",
    discovered: 0,
    added: 0,
    updated: 0,
    requeued: 0,
    skippedReady: 0,
    markedMissing: 0,
    restored: 0,
    pruned: 0,
    durationMs: 0,
  };

  if (state.running) {
    return { ...base, error: "A sync is already running", durationMs: 0 };
  }
  state.running = true;

  try {
    await ensureSchema();
    const config = await getAutoSyncConfig();

    const { files, mode: scanMode } = await scanLibrary();
    const offcloudMode: "real" | "mock" = scanMode === "error" ? "real" : scanMode;
    base.offcloudMode = offcloudMode;
    base.discovered = files.length;

    const fingerprint = libraryFingerprint(files);
    const unchanged = fingerprint === state.fingerprint;

    // Fast path: nothing on Offcloud changed and we are not forcing a full
    // reconcile. Zero writes — this is what makes 1-second polling viable.
    if (unchanged && mode === "delta" && !force) {
      state.lastSyncAt = new Date().toISOString();
      state.totalSyncs += 1;
      state.consecutiveErrors = 0;
      const result = { ...base, changed: false, durationMs: Date.now() - startedAt };
      state.lastResult = result;
      return result;
    }

    const seenAt = new Date();
    const seenKeys: string[] = [];
    let added = 0;
    let updated = 0;
    let requeued = 0;
    let skippedReady = 0;
    let restored = 0;

    for (const file of files) {
      const key = contentKeyOf(file);
      const hash = contentHashOf(file);
      seenKeys.push(key);

      const existing = await db.video.findFirst({
        // Scope to Offcloud rows: TeraBox/Blomp ids live in the same table and
        // must never be matched (or reconciled) by this engine.
        where: { source: "offcloud", offcloudId: file.offcloudId, name: file.name },
      });

      if (!existing) {
        // Brand-new content — index it and queue the detection pipeline.
        const created = await db.video.create({
          data: {
            source: "offcloud",
            offcloudId: file.offcloudId,
            name: file.name,
            folderPath: file.folderPath,
            streamUrl: file.streamUrl,
            size: file.size,
            duration: file.duration ?? null,
            addedAt: file.addedAt ?? null,
            status: "pending",
            availability: "available",
            lastSeenAt: seenAt,
            contentKey: key,
            contentHash: hash,
          },
        });
        await enqueue(created.id);
        added++;
        requeued++;
        continue;
      }

      const bytesChanged = existing.contentHash != null && existing.contentHash !== hash;
      const wasMissing = existing.availability !== "available";
      const alreadyReady = existing.status === "ready";

      // Always keep the stream URL and presence bookkeeping fresh: Offcloud URLs
      // expire, and this is cheap compared with re-analysis.
      await db.video.update({
        where: { id: existing.id },
        data: {
          streamUrl: file.streamUrl,
          folderPath: file.folderPath,
          size: file.size,
          addedAt: file.addedAt ?? existing.addedAt,
          availability: "available",
          missingSince: null,
          lastSeenAt: seenAt,
          contentKey: key,
          contentHash: hash,
          // Status is deliberately untouched: a "ready" video stays ready.
          ...(bytesChanged || force ? { status: "pending" } : {}),
        },
      });
      updated++;
      if (wasMissing) restored++;

      if (alreadyReady && !bytesChanged && !force) {
        // The whole point: already loaded and playable, so do nothing.
        skippedReady++;
        continue;
      }

      if (await enqueue(existing.id)) requeued++;
    }

    // ---- Content deleted from Offcloud -----------------------------------
    // Only trust deletions when we really talked to Offcloud. In mock mode, or
    // when the listing came back empty because of an API error, we leave the
    // library alone rather than hiding everything.
    let markedMissing = 0;
    let pruned = 0;
    const deletionsTrustworthy = scanMode === "real" && files.length > 0;

    if (deletionsTrustworthy) {
      const vanished = await db.video.findMany({
        where: {
          // Source-scoped: an Offcloud poll only owns Offcloud rows. Without
          // this, every Blomp/TeraBox video would be marked missing on the
          // first poll because it was never in the Offcloud listing.
          source: "offcloud",
          availability: "available",
          OR: [{ lastSeenAt: null }, { lastSeenAt: { lt: seenAt } }],
        },
        select: { id: true, name: true },
      });
      if (vanished.length > 0) {
        await db.video.updateMany({
          where: { id: { in: vanished.map((v) => v.id) } },
          data: { availability: "missing", missingSince: seenAt },
        });
        // Drop any pending analysis for content that no longer exists.
        await db.queueItem.deleteMany({
          where: {
            videoId: { in: vanished.map((v) => v.id) },
            status: { in: ["queued", "running"] },
          },
        });
        markedMissing = vanished.length;
        console.log(`${LOG} ${markedMissing} item(s) removed from Offcloud — hidden from library and feed`);
      }

      // Purge rows that have been gone longer than the grace period.
      if (config.pruneAfterHours > 0) {
        const cutoff = new Date(Date.now() - config.pruneAfterHours * 3600_000);
        const { count } = await db.video.deleteMany({
          where: {
            source: "offcloud",
            availability: "missing",
            missingSince: { lt: cutoff },
          },
        });
        pruned = count;
      }
    }

    // Start the detection worker whenever anything is waiting - not only on the
    // poll that queued it. This lets a stalled queue recover by itself.
    const waiting = await db.queueItem.count({ where: { status: "queued" } });
    if (waiting > 0) {
      const { ensureQueueProcessing } = await import("./scan-engine");
      void ensureQueueProcessing(offcloudMode);
    }

    state.fingerprint = fingerprint;
    state.lastSyncAt = new Date().toISOString();
    state.totalSyncs += 1;
    state.consecutiveErrors = 0;

    const changed =
      added > 0 || requeued > 0 || markedMissing > 0 || restored > 0 || pruned > 0;
    if (changed) state.lastChangeAt = state.lastSyncAt;

    const result: SyncResult = {
      ...base,
      changed,
      added,
      updated,
      requeued,
      skippedReady,
      markedMissing,
      restored,
      pruned,
      durationMs: Date.now() - startedAt,
    };
    state.lastResult = result;

    if (changed || mode === "full") {
      console.log(
        `${LOG} ${mode}/${trigger}: ${base.discovered} on Offcloud, +${added} new, ${skippedReady} already ready (skipped), ${requeued} queued, ${markedMissing} removed, ${pruned} purged (${result.durationMs}ms)`
      );
    }
    return result;
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    state.consecutiveErrors += 1;
    const result: SyncResult = { ...base, error: msg, durationMs: Date.now() - startedAt };
    state.lastResult = result;
    console.warn(`${LOG} failed: ${msg}`);
    return result;
  } finally {
    state.running = false;
  }
}

/** Queue a video for detection unless it is already waiting. Returns true if queued. */
async function enqueue(videoId: string): Promise<boolean> {
  const existing = await db.queueItem.findFirst({
    where: { videoId, status: { in: ["queued", "running"] } },
  });
  if (existing) return false;
  await db.queueItem.create({
    data: { videoId, status: "queued", currentStep: null, stepProgress: 0 },
  });
  return true;
}

// ---------------------------------------------------------------------------
// Auto-sync loop
// ---------------------------------------------------------------------------

function scheduleNextPoll(overrideSeconds?: number): void {
  const state = rt();
  if (state.timer) {
    clearTimeout(state.timer);
    state.timer = null;
  }

  const config = state.config;
  if (!config || !config.enabled) {
    state.nextPollAt = null;
    return;
  }

  // Exponential backoff while Offcloud is unhappy, so a 1s interval cannot turn
  // into a hammering loop against a failing API.
  const backoff =
    state.consecutiveErrors > 0
      ? Math.min(
          MAX_BACKOFF_SECONDS,
          config.intervalSeconds * Math.pow(2, Math.min(state.consecutiveErrors, 6))
        )
      : config.intervalSeconds;

  const seconds = overrideSeconds ?? backoff;
  state.nextPollAt = Date.now() + seconds * 1000;

  state.timer = setTimeout(async () => {
    try {
      await syncOnce({ mode: "delta", trigger: "auto" });
    } catch {
      // syncOnce never throws, but stay defensive inside a timer.
    }
    scheduleNextPoll();
  }, Math.max(250, seconds * 1000));

  state.timer.unref?.();
}

/**

 * Start continuous syncing. Called from src/instrumentation.ts on every server

 * boot — including when a Hugging Face Space wakes from sleep or pause, which

 * is exactly when the full reconcile is needed.

 */
export async function startAutoSync(): Promise<SyncState> {
  const state = rt();
  const config = await getAutoSyncConfig();
  state.config = config;

  if (!state.started) {
    state.started = true;
    console.log(
      `${LOG} auto-sync online — every ${config.intervalSeconds}s, prune after ${

        config.pruneAfterHours || "never"

      }h`
    );

    if (config.fullSyncOnBoot) {
      // Cold start / wake from sleep: reconcile and load the entire library.
      await syncOnce({ mode: "full", trigger: "boot" }).catch(() => {});
    }
  }

  scheduleNextPoll();
  return getSyncState();
}

export function getSyncState(): SyncState {
  const state = rt();
  return {
    running: state.running,
    loopArmed: Boolean(state.timer),
    lastSyncAt: state.lastSyncAt,
    lastChangeAt: state.lastChangeAt,
    lastResult: state.lastResult,
    totalSyncs: state.totalSyncs,
    consecutiveErrors: state.consecutiveErrors,
    nextPollInSeconds: state.nextPollAt
      ? Math.max(0, Math.round((state.nextPollAt - Date.now()) / 1000))
      : null,
    libraryFingerprint: state.fingerprint,
  };
}

/** Library counts for the sync status card. */
export async function getLibraryCounts() {
  const [available, missing, ready, pending, queued] = await Promise.all([
    db.video.count({ where: { availability: "available" } }),
    db.video.count({ where: { availability: "missing" } }),
    db.video.count({ where: { availability: "available", status: "ready" } }),
    db.video.count({ where: { availability: "available", status: { in: ["pending", "scanning"] } } }),
    db.queueItem.count({ where: { status: { in: ["queued", "running"] } } }),
  ]);
  return { available, missing, ready, pending, queued };
}