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
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import crypto from 'node:crypto';
import { encryptSecret, decryptSecret, hashPassword } from './crypto.js';
import type { AIRoleRoutingEntry, AIProviderProfile, BrandKit, FrozenRecipe } from '@olokaflow/shared';

function resolveWritableDataDir(): string {
  const candidates = [
    process.env.DATA_DIR,
    path.join(process.cwd(), 'data'),
    '/tmp/olokaflow',
  ].filter(Boolean) as string[];

  for (const candidate of candidates) {
    try {
      const resolved = path.resolve(candidate);
      fs.mkdirSync(resolved, { recursive: true });
      const probeFile = path.join(resolved, '.write-probe');
      fs.writeFileSync(probeFile, 'ok');
      fs.unlinkSync(probeFile);
      return resolved;
    } catch {
      // Try next writable directory
    }
  }
  return path.resolve('/tmp/olokaflow');
}

export const DATA_DIR = resolveWritableDataDir();
export const PROJECTS_DIR = path.join(DATA_DIR, 'projects');
export const UPLOADS_DIR = path.join(DATA_DIR, 'uploads');
export const AUDIO_CACHE_DIR = path.join(DATA_DIR, 'audio_cache');
export const RENDERS_DIR = path.join(DATA_DIR, 'renders');
export const DB_PATH = path.join(DATA_DIR, 'olokaflow.sqlite');

for (const dir of [DATA_DIR, PROJECTS_DIR, UPLOADS_DIR, AUDIO_CACHE_DIR, RENDERS_DIR]) {
  fs.mkdirSync(dir, { recursive: true });
}

export const db = new DatabaseSync(DB_PATH);

db.exec(`
  PRAGMA journal_mode = WAL;
  PRAGMA synchronous = NORMAL;
  PRAGMA foreign_keys = ON;

  CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY,
    email TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'creator',
    password_hash TEXT NOT NULL,
    token_quota INTEGER NOT NULL DEFAULT 1000000,
    tokens_used INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS sessions (
    token TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    expires_at TEXT NOT NULL,
    created_at TEXT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
  );

  CREATE TABLE IF NOT EXISTS ai_provider_profiles (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    protocol TEXT NOT NULL,
    base_url TEXT NOT NULL,
    encrypted_api_key TEXT NOT NULL DEFAULT '',
    custom_headers_json TEXT NOT NULL DEFAULT '{}',
    timeout_ms INTEGER NOT NULL DEFAULT 180000,
    max_concurrency INTEGER NOT NULL DEFAULT 4,
    enabled INTEGER NOT NULL DEFAULT 1,
    notes TEXT NOT NULL DEFAULT '',
    health_status TEXT NOT NULL DEFAULT 'untested',
    last_tested_at TEXT,
    last_latency_ms INTEGER,
    last_test_message TEXT NOT NULL DEFAULT '',
    models_json TEXT NOT NULL DEFAULT '[]',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS ai_role_routings (
    role TEXT PRIMARY KEY,
    label TEXT NOT NULL,
    description TEXT NOT NULL,
    primary_profile_id TEXT NOT NULL DEFAULT '',
    primary_model_id TEXT NOT NULL DEFAULT '',
    fallback_profile_id TEXT NOT NULL DEFAULT '',
    fallback_model_id TEXT NOT NULL DEFAULT '',
    updated_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS brand_kits (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    data_json TEXT NOT NULL,
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS frozen_recipes (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    data_json TEXT NOT NULL,
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS assets (
    id TEXT PRIMARY KEY,
    project_id TEXT,
    name TEXT NOT NULL,
    type TEXT NOT NULL,
    source TEXT NOT NULL,
    source_url TEXT NOT NULL DEFAULT '',
    relative_path TEXT NOT NULL,
    public_url TEXT NOT NULL,
    mime_type TEXT NOT NULL,
    size_bytes INTEGER NOT NULL DEFAULT 0,
    width INTEGER NOT NULL DEFAULT 1080,
    height INTEGER NOT NULL DEFAULT 1080,
    duration_sec REAL NOT NULL DEFAULT 0,
    collection TEXT NOT NULL DEFAULT 'general',
    brand_tag TEXT NOT NULL DEFAULT '',
    analysis_status TEXT NOT NULL DEFAULT 'ready',
    analysis_json TEXT NOT NULL DEFAULT '{}',
    embedding_json TEXT NOT NULL DEFAULT '[]',
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS projects (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    title TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'draft',
    aspect_ratio TEXT NOT NULL DEFAULT '9:16',
    data_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS project_versions (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL,
    version_num INTEGER NOT NULL,
    label TEXT NOT NULL,
    snapshot_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
  );

  CREATE TABLE IF NOT EXISTS render_jobs (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL,
    provider TEXT NOT NULL DEFAULT 'modal',
    status TEXT NOT NULL DEFAULT 'queued',
    progress INTEGER NOT NULL DEFAULT 0,
    data_json TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS usage_ledger (
    id TEXT PRIMARY KEY,
    project_id TEXT,
    profile_id TEXT,
    model_id TEXT,
    role TEXT NOT NULL,
    prompt_tokens INTEGER NOT NULL DEFAULT 0,
    completion_tokens INTEGER NOT NULL DEFAULT 0,
    tts_chars INTEGER NOT NULL DEFAULT 0,
    images_count INTEGER NOT NULL DEFAULT 0,
    render_seconds REAL NOT NULL DEFAULT 0,
    duration_ms INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS system_settings (
    key TEXT PRIMARY KEY,
    value_json TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS custom_voices (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    voice_id TEXT NOT NULL,
    gender TEXT NOT NULL DEFAULT 'Nam',
    region TEXT NOT NULL DEFAULT 'Việt Nam',
    description TEXT NOT NULL DEFAULT '',
    ref_text TEXT NOT NULL DEFAULT '',
    sample_audio_path TEXT NOT NULL DEFAULT '',
    sample_public_url TEXT NOT NULL DEFAULT '',
    fallback_voice_id TEXT NOT NULL DEFAULT 'Hải Đăng',
    created_at TEXT NOT NULL
  );

  CREATE TABLE IF NOT EXISTS batch_jobs (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'running',
    total_items INTEGER NOT NULL DEFAULT 0,
    completed_items INTEGER NOT NULL DEFAULT 0,
    failed_items INTEGER NOT NULL DEFAULT 0,
    config_json TEXT NOT NULL DEFAULT '{}',
    items_json TEXT NOT NULL DEFAULT '[]',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );
`);

export function seedInitialDatabase(): void {
  const now = new Date().toISOString();

  // 1. Seed default Admin & Creator users
  const userCount = (db.prepare('SELECT COUNT(*) as c FROM users').get() as { c: number }).c;
  if (userCount === 0) {
    const insertUser = db.prepare(`
      INSERT INTO users (id, email, name, role, password_hash, token_quota, tokens_used, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `);
    insertUser.run(
      'usr-admin',
      'admin@olokaflow.ai',
      'OlokaFlow Admin',
      'admin',
      hashPassword('admin123'),
      50000000,
      0,
      now
    );
    insertUser.run(
      'usr-creator',
      'creator@olokaflow.ai',
      'Video Creator Pro',
      'creator',
      hashPassword('creator123'),
      5000000,
      0,
      now
    );
  }

  // 2. Seed starter AI Provider Profiles if empty
  const profileCount = (db.prepare('SELECT COUNT(*) as c FROM ai_provider_profiles').get() as { c: number }).c;
  if (profileCount === 0) {
    const starterProfiles: Omit<AIProviderProfile, 'hasApiKey' | 'maskedApiKey'>[] = [
      {
        id: 'prof-self-hosted-llm',
        name: 'Custom OpenAI-Compatible Gateway (vLLM / LiteLLM / Proxy)',
        protocol: 'openai-compatible',
        baseUrl: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
        apiKey: process.env.OPENAI_API_KEY || '',
        customHeaders: {},
        timeoutMs: 240000,
        maxConcurrency: 4,
        enabled: true,
        notes: 'Cổng LLM tự host hoặc OpenRouter / Xiaomi MiMo / DeepSeek theo chuẩn OpenAI',
        healthStatus: 'untested',
        lastTestedAt: null,
        lastLatencyMs: null,
        lastTestMessage: 'Chưa kiểm tra kết nối',
        models: [
          {
            id: 'mdl-gpt4o',
            modelId: 'gpt-4o',
            name: 'GPT-4o (Multimodal + Code)',
            ownedBy: 'openai',
            capabilities: ['chat', 'coding', 'vision', 'json_mode', 'tool_calling'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 8192,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-qwen-coder',
            modelId: 'qwen-2.5-coder-32b-instruct',
            name: 'Qwen 2.5 Coder 32B (HyperFrames HTML/GSAP)',
            ownedBy: 'qwen',
            capabilities: ['chat', 'coding', 'json_mode'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 8192,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-deepseek-r1',
            modelId: 'deepseek-reasoner',
            name: 'DeepSeek R1 / Reasoner (Director Storyboard)',
            ownedBy: 'deepseek',
            capabilities: ['chat', 'reasoning', 'json_mode'],
            supportsThinking: true,
            reasoningEffort: 'medium',
            maxTokens: 8192,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
        ],
        createdAt: now,
        updatedAt: now,
      },
      {
        id: 'prof-gemini-hub',
        name: 'Google Gemini OpenAI-Compatible Hub',
        protocol: 'gemini',
        baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',
        apiKey: process.env.GEMINI_API_KEY || '',
        customHeaders: {},
        timeoutMs: 180000,
        maxConcurrency: 6,
        enabled: true,
        notes: 'Gemini 2.5 Pro & Flash cho phân tích ảnh/video đa phương thức và sinh code tốc độ cao',
        healthStatus: 'untested',
        lastTestedAt: null,
        lastLatencyMs: null,
        lastTestMessage: 'Chưa kiểm tra kết nối',
        models: [
          {
            id: 'mdl-gemini-25-flash',
            modelId: 'gemini-2.5-flash',
            name: 'Gemini 2.5 Flash (Vision + Fast Coder)',
            ownedBy: 'google',
            capabilities: ['chat', 'coding', 'vision', 'reasoning', 'json_mode'],
            supportsThinking: true,
            reasoningEffort: 'low',
            maxTokens: 8192,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-gemini-25-pro',
            modelId: 'gemini-2.5-pro',
            name: 'Gemini 2.5 Pro (Deep Director & Motion Architect)',
            ownedBy: 'google',
            capabilities: ['chat', 'coding', 'vision', 'reasoning', 'json_mode'],
            supportsThinking: true,
            reasoningEffort: 'medium',
            maxTokens: 8192,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
        ],
        createdAt: now,
        updatedAt: now,
      },
      {
        id: 'prof-openai-voice',
        name: 'OlokaTTS & OpenAI Voice Gateway (https://tts.oloka.net)',
        protocol: 'openai-voice',
        baseUrl: process.env.VOICE_BASE_URL || 'https://tts.oloka.net',
        apiKey: process.env.VOICE_API_KEY || process.env.OPENAI_API_KEY || '',
        customHeaders: {},
        timeoutMs: 120000,
        maxConcurrency: 3,
        enabled: true,
        notes: 'Chuẩn OlokaTTS (25 giọng Việt Nam tại https://tts.oloka.net) & OpenAI /v1/audio/speech + /v1/audio/transcriptions',
        healthStatus: 'untested',
        lastTestedAt: null,
        lastLatencyMs: null,
        lastTestMessage: 'Chưa kiểm tra kết nối',
        models: [
          {
            id: 'mdl-olokatts-v3',
            modelId: 'olokatts-v3-turbo',
            name: 'OlokaTTS v3 Turbo (25 Giọng Việt Nam)',
            ownedBy: 'oloka',
            capabilities: ['tts'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 4096,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-tts-1-hd',
            modelId: 'tts-1-hd',
            name: 'OpenAI TTS-1-HD',
            ownedBy: 'openai',
            capabilities: ['tts'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 4096,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-whisper-1',
            modelId: 'whisper-1',
            name: 'Whisper Word Timestamp ASR',
            ownedBy: 'voice-gateway',
            capabilities: ['asr'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 4096,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
        ],
        createdAt: now,
        updatedAt: now,
      },
      {
        id: 'prof-hf-pro-image',
        name: 'Hugging Face Pro Inference (FLUX.1 Reference Image Gen)',
        protocol: 'huggingface',
        baseUrl: 'https://router.huggingface.co/hf-inference/models',
        apiKey: process.env.HF_TOKEN || '',
        customHeaders: {},
        timeoutMs: 120000,
        maxConcurrency: 3,
        enabled: true,
        notes: 'Tạo hình ảnh tham khảo tốc độ cao qua tài khoản Hugging Face Pro (FLUX.1-schnell / FLUX.1-dev)',
        healthStatus: 'untested',
        lastTestedAt: null,
        lastLatencyMs: null,
        lastTestMessage: 'Chưa kiểm tra kết nối',
        models: [
          {
            id: 'mdl-flux-schnell',
            modelId: 'black-forest-labs/FLUX.1-schnell',
            name: 'FLUX.1 Schnell (Siêu tốc 2s/ảnh)',
            ownedBy: 'black-forest-labs',
            capabilities: ['image_gen'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 1024,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-flux-dev',
            modelId: 'black-forest-labs/FLUX.1-dev',
            name: 'FLUX.1 Dev (Chất lượng Điện ảnh)',
            ownedBy: 'black-forest-labs',
            capabilities: ['image_gen'],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 1024,
            healthStatus: 'untested',
            lastTestedAt: null,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
        ],
        createdAt: now,
        updatedAt: now,
      },
      {
        id: 'prof-modal-renderer',
        name: 'Modal Serverless HyperFrames Renderer (Production)',
        protocol: 'modal-render',
        baseUrl:
          process.env.MODAL_RENDER_BASE_URL ||
          process.env.MODAL_RENDER_URL ||
          'https://phucsd--autocode-hyperframes-renderer-web.modal.run',
        apiKey:
          process.env.MODAL_RENDER_API_TOKEN ||
          process.env.MODAL_RENDER_TOKEN ||
          '',
        customHeaders: {},
        timeoutMs: 600000,
        maxConcurrency: 4,
        enabled: true,
        notes: 'Modal Cloud HyperFrames Renderer (cpu24w22 / cpu10w8 • Chromium + FFmpeg H.264)',
        healthStatus: 'healthy',
        lastTestedAt: now,
        lastLatencyMs: 240,
        lastTestMessage: 'Modal HyperFrames Renderer v0.7.90 Ready',
        models: [
          {
            id: 'mdl-modal-cpu24w22',
            modelId: 'cpu24w22',
            name: 'Modal Ultra (24 vCPU • 22 Workers • 8GB RAM)',
            ownedBy: 'modal',
            capabilities: [],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 0,
            healthStatus: 'healthy',
            lastTestedAt: now,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
          {
            id: 'mdl-modal-cpu10w8',
            modelId: 'cpu10w8',
            name: 'Modal Pro (10 vCPU • 8 Workers • 8GB RAM)',
            ownedBy: 'modal',
            capabilities: [],
            supportsThinking: false,
            reasoningEffort: 'none',
            maxTokens: 0,
            healthStatus: 'healthy',
            lastTestedAt: now,
            ttftMs: null,
            durationMs: null,
            lastTestMessage: '',
          },
        ],
        createdAt: now,
        updatedAt: now,
      },
    ];

    const insertProfile = db.prepare(`
      INSERT INTO ai_provider_profiles (
        id, name, protocol, base_url, encrypted_api_key, custom_headers_json,
        timeout_ms, max_concurrency, enabled, notes, health_status,
        last_tested_at, last_latency_ms, last_test_message, models_json,
        created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);

    for (const p of starterProfiles) {
      insertProfile.run(
        p.id,
        p.name,
        p.protocol,
        p.baseUrl,
        encryptSecret(p.apiKey),
        JSON.stringify(p.customHeaders),
        p.timeoutMs,
        p.maxConcurrency,
        p.enabled ? 1 : 0,
        p.notes,
        p.healthStatus,
        p.lastTestedAt,
        p.lastLatencyMs,
        p.lastTestMessage,
        JSON.stringify(p.models),
        p.createdAt,
        p.updatedAt
      );
    }
  }

  backfillProfileSecretsFromEnv();

  // 3. Seed Role Routing Matrix if empty
  const routingCount = (db.prepare('SELECT COUNT(*) as c FROM ai_role_routings').get() as { c: number }).c;
  if (routingCount === 0) {
    const defaultRoutings: AIRoleRoutingEntry[] = [
      {
        role: 'director',
        label: '🎬 Director & Storyboard Agent',
        description: 'Phân tích yêu cầu, lập kịch bản JSON, chọn Blueprint & Motion Rules cho từng cảnh',
        primaryProfileId: 'prof-self-hosted-llm',
        primaryModelId: 'gpt-4o',
        fallbackProfileId: 'prof-gemini-hub',
        fallbackModelId: 'gemini-2.5-pro',
      },
      {
        role: 'frame_worker',
        label: '💻 Frame Worker Coding Agent',
        description: 'Sinh code HTML5 + CSS + GSAP Sub-compositions chuẩn HyperFrames cho từng phân cảnh',
        primaryProfileId: 'prof-self-hosted-llm',
        primaryModelId: 'qwen-2.5-coder-32b-instruct',
        fallbackProfileId: 'prof-gemini-hub',
        fallbackModelId: 'gemini-2.5-flash',
      },
      {
        role: 'surgical_edit',
        label: '🛠️ Surgical Edit & Self-Healing Agent',
        description: 'Chỉnh sửa cục bộ phân cảnh qua Prompt và tự động vá lỗi hyperframes lint',
        primaryProfileId: 'prof-self-hosted-llm',
        primaryModelId: 'gpt-4o',
        fallbackProfileId: 'prof-gemini-hub',
        fallbackModelId: 'gemini-2.5-flash',
      },
      {
        role: 'vision_analyzer',
        label: '👁️ Multimodal Vision & Video Analyzer',
        description: 'Phân tích ảnh cào về, đọc chữ OCR trên sản phẩm, nhận diện thương hiệu và cắt đoạn B-roll video',
        primaryProfileId: 'prof-gemini-hub',
        primaryModelId: 'gemini-2.5-flash',
        fallbackProfileId: 'prof-self-hosted-llm',
        fallbackModelId: 'gpt-4o',
      },
      {
        role: 'embedding',
        label: '🧭 Vector Embedding & Asset Search',
        description: 'Chuyển đổi hồ sơ tài nguyên thành vector để khớp ảnh/video vào đúng cảnh',
        primaryProfileId: 'prof-self-hosted-llm',
        primaryModelId: 'text-embedding-3-small',
        fallbackProfileId: '',
        fallbackModelId: '',
      },
      {
        role: 'voice_tts',
        label: '🎙️ Voice Speech Synthesis (OlokaTTS & OpenAI TTS)',
        description: 'Sinh giọng đọc tự nhiên chuẩn OlokaTTS (https://tts.oloka.net) & OpenAI /v1/audio/speech',
        primaryProfileId: 'prof-openai-voice',
        primaryModelId: 'olokatts-v3-turbo',
        fallbackProfileId: '',
        fallbackModelId: '',
      },
      {
        role: 'voice_asr',
        label: '📝 Word Timestamp Transcription (ASR)',
        description: 'Trích xuất mốc thời gian từng từ chuẩn /v1/audio/transcriptions cho phụ đề Karaoke',
        primaryProfileId: 'prof-openai-voice',
        primaryModelId: 'whisper-1',
        fallbackProfileId: '',
        fallbackModelId: '',
      },
      {
        role: 'image_gen',
        label: '🖼️ Reference Image Generator',
        description: 'Tạo hình ảnh tham khảo tự động cho phân cảnh (Hugging Face Pro FLUX.1 / OpenAI Images)',
        primaryProfileId: 'prof-hf-pro-image',
        primaryModelId: 'black-forest-labs/FLUX.1-schnell',
        fallbackProfileId: 'prof-self-hosted-llm',
        fallbackModelId: 'dall-e-3',
      },
      {
        role: 'modal_render',
        label: '☁️ Modal Serverless Video Renderer',
        description: 'Kết nối Modal HyperFrames Renderer (cpu24w22 / cpu10w8 • Chromium + FFmpeg H.264)',
        primaryProfileId: 'prof-modal-renderer',
        primaryModelId: 'cpu24w22',
        fallbackProfileId: '',
        fallbackModelId: '',
      },
    ];

    const insertRouting = db.prepare(`
      INSERT INTO ai_role_routings (
        role, label, description, primary_profile_id, primary_model_id,
        fallback_profile_id, fallback_model_id, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `);

    for (const r of defaultRoutings) {
      insertRouting.run(
        r.role,
        r.label,
        r.description,
        r.primaryProfileId,
        r.primaryModelId,
        r.fallbackProfileId,
        r.fallbackModelId,
        now
      );
    }
  }

  // Upgrade any legacy placeholder URLs in existing DB rows
  db.prepare(`
    UPDATE ai_provider_profiles
    SET base_url = 'https://phucsd--autocode-hyperframes-renderer-web.modal.run',
        name = 'Modal Serverless HyperFrames Renderer (Production)',
        health_status = 'healthy',
        last_test_message = 'Modal HyperFrames Renderer v0.7.90 Ready'
    WHERE id = 'prof-modal-renderer' AND base_url LIKE '%your-workspace%'
  `).run();

  db.prepare(`
    UPDATE ai_provider_profiles
    SET base_url = 'https://tts.oloka.net',
        name = 'OlokaTTS & OpenAI Voice Gateway (https://tts.oloka.net)'
    WHERE id = 'prof-openai-voice' AND base_url = 'https://api.openai.com/v1' AND encrypted_api_key = ''
  `).run();

  // 4. Seed starter Brand Kits & Frozen Recipes
  const brandCount = (db.prepare('SELECT COUNT(*) as c FROM brand_kits').get() as { c: number }).c;
  if (brandCount === 0) {
    const starterBrands: BrandKit[] = [
      {
        id: 'brk-oloka-tech',
        name: 'Oloka Tech SaaS (Cobalt & Cream)',
        brandName: 'OlokaFlow AI',
        logoUrl: '',
        primaryColor: '#1e2bfa',
        secondaryColor: '#0f172a',
        bgColor: '#fdfae7',
        textColor: '#0f172a',
        headingFont: 'Space Grotesk',
        bodyFont: 'Be Vietnam Pro',
        defaultVoiceId: 'alloy',
        defaultCtaText: 'Bắt đầu tạo video AI chuyên nghiệp tại OlokaFlow.ai',
        websiteUrl: 'https://olokaflow.ai',
        createdAt: now,
      },
      {
        id: 'brk-luxury-gold',
        name: 'Premium E-Commerce & Beauty (Gold & Obsidian)',
        brandName: 'Aura Luxury',
        logoUrl: '',
        primaryColor: '#f59e0b',
        secondaryColor: '#fef3c7',
        bgColor: '#090d16',
        textColor: '#f8fafc',
        headingFont: 'Playfair Display',
        bodyFont: 'Be Vietnam Pro',
        defaultVoiceId: 'nova',
        defaultCtaText: 'Đặt hàng chính hãng ngay hôm nay — Ưu đãi 30%',
        websiteUrl: '',
        createdAt: now,
      },
    ];
    const insertBrand = db.prepare('INSERT INTO brand_kits (id, name, data_json, created_at) VALUES (?, ?, ?, ?)');
    for (const b of starterBrands) {
      insertBrand.run(b.id, b.name, JSON.stringify(b), now);
    }
  }

  const recipeCount = (db.prepare('SELECT COUNT(*) as c FROM frozen_recipes').get() as { c: number }).c;
  if (recipeCount === 0) {
    const starterRecipes: FrozenRecipe[] = [
      {
        id: 'rcp-tiktok-viral-5scenes',
        name: 'TikTok / Reels Sản Phẩm Viral (5 Cảnh Chuẩn)',
        description: 'Công thức 5 phân cảnh tốc độ cao: Hook gây tò mò -> Nỗi đau -> Ra mắt sản phẩm -> Tính năng & Số liệu -> CTA khóa thương hiệu',
        framePresetId: 'blockframe',
        aspectRatio: '9:16',
        sceneTemplates: [
          {
            role: 'Hook',
            blueprintId: 'kinetic-type-beats',
            motionRuleIds: ['kinetic-beat-slam', 'spring-pop-entrance'],
            registryBlockName: 'quote-card',
            durationSec: 3.5,
          },
          {
            role: 'Problem',
            blueprintId: 'overwhelm-surround',
            motionRuleIds: ['chromatic-glitch', 'waterfall-entry'],
            registryBlockName: '',
            durationSec: 4.5,
          },
          {
            role: 'Product_Intro',
            blueprintId: 'device-surface-showcase',
            motionRuleIds: ['3d-camera-flight', 'spring-pop-entrance'],
            registryBlockName: 'app-showcase',
            durationSec: 5.0,
          },
          {
            role: 'Data_Proof',
            blueprintId: 'dataviz-countup',
            motionRuleIds: ['counting-dynamic-scale', 'chart-scrub-readout'],
            registryBlockName: 'data-chart',
            durationSec: 5.0,
          },
          {
            role: 'CTA',
            blueprintId: 'logo-assemble-lockup',
            motionRuleIds: ['spring-pop-entrance', 'particle-burst'],
            registryBlockName: 'logo-outro',
            durationSec: 4.0,
          },
        ],
        createdAt: now,
      },
      {
        id: 'rcp-saas-launch-16x9',
        name: 'SaaS / Tech Product Launch (16:9 YouTube & Landing Page)',
        description: 'Video giới thiệu phần mềm/công nghệ chuyên nghiệp với hiệu ứng gõ lệnh, giao diện trực quan và biểu đồ tăng trưởng',
        framePresetId: 'blue-professional',
        aspectRatio: '16:9',
        sceneTemplates: [
          {
            role: 'Hook',
            blueprintId: 'typewriter-reveal',
            motionRuleIds: ['discrete-text-sequence', 'context-sensitive-cursor'],
            registryBlockName: '',
            durationSec: 4.0,
          },
          {
            role: 'Product_Intro',
            blueprintId: 'prompt-type-submit-generate',
            motionRuleIds: ['cursor-click-ripple', 'spring-pop-entrance'],
            registryBlockName: 'app-showcase',
            durationSec: 5.5,
          },
          {
            role: 'Key_Feature',
            blueprintId: 'cursor-ui-demo',
            motionRuleIds: ['coordinate-target-zoom', '3d-camera-flight'],
            registryBlockName: 'flowchart',
            durationSec: 6.0,
          },
          {
            role: 'Benefits',
            blueprintId: 'grid-card-assemble',
            motionRuleIds: ['waterfall-entry', 'counting-dynamic-scale'],
            registryBlockName: 'data-chart',
            durationSec: 5.0,
          },
          {
            role: 'CTA',
            blueprintId: 'cta-morph-press',
            motionRuleIds: ['physics-press-reaction', 'spring-pop-entrance'],
            registryBlockName: 'logo-outro',
            durationSec: 4.0,
          },
        ],
        createdAt: now,
      },
    ];
    const insertRecipe = db.prepare('INSERT INTO frozen_recipes (id, name, data_json, created_at) VALUES (?, ?, ?, ?)');
    for (const r of starterRecipes) {
      insertRecipe.run(r.id, r.name, JSON.stringify(r), now);
    }
  }

  // 5. Seed default system settings
  const settingsCount = (db.prepare('SELECT COUNT(*) as c FROM system_settings').get() as { c: number }).c;
  if (settingsCount === 0) {
    const defaultSettings = {
      jevEnabled: true,
      jevConfidenceThreshold: 0.72,
      hfVaultEnabled: Boolean(process.env.HF_TOKEN && process.env.HF_VAULT_DATASET_REPO),
      hfVaultDatasetRepo: process.env.HF_VAULT_DATASET_REPO || '',
      hfVaultLastSyncAt: null,
      autoFallbackEnabled: true,
      defaultAspectRatio: '9:16',
      defaultCreationMode: 'auto',
      defaultFramePresetId: 'blue-professional',
    };
    db.prepare('INSERT INTO system_settings (key, value_json, updated_at) VALUES (?, ?, ?)').run(
      'global',
      JSON.stringify(defaultSettings),
      now
    );
  }
}

export function logUsage(entry: {
  projectId?: string | null;
  profileId?: string | null;
  modelId?: string | null;
  role: string;
  promptTokens?: number;
  completionTokens?: number;
  ttsChars?: number;
  imagesCount?: number;
  renderSeconds?: number;
  durationMs?: number;
}): void {
  try {
    db.prepare(`
      INSERT INTO usage_ledger (
        id, project_id, profile_id, model_id, role,
        prompt_tokens, completion_tokens, tts_chars, images_count,
        render_seconds, duration_ms, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
      `usg-${crypto.randomUUID().slice(0, 8)}`,
      entry.projectId || null,
      entry.profileId || null,
      entry.modelId || null,
      entry.role,
      entry.promptTokens || 0,
      entry.completionTokens || 0,
      entry.ttsChars || 0,
      entry.imagesCount || 0,
      entry.renderSeconds || 0,
      entry.durationMs || 0,
      new Date().toISOString()
    );
  } catch (err) {
    console.warn('[UsageLedger] Failed to log usage:', err);
  }
}

export function backfillProfileSecretsFromEnv(): void {
  const envMapping: Record<string, string | undefined> = {
    'prof-self-hosted-llm': process.env.OPENAI_API_KEY,
    'prof-gemini-hub': process.env.GEMINI_API_KEY,
    'prof-openai-voice': process.env.VOICE_API_KEY || process.env.OPENAI_API_KEY,
    'prof-hf-pro-image': process.env.HF_TOKEN,
    'prof-modal-renderer': process.env.MODAL_RENDER_API_TOKEN || process.env.MODAL_RENDER_TOKEN,
  };

  try {
    const rows = db
      .prepare('SELECT id, encrypted_api_key FROM ai_provider_profiles')
      .all() as { id: string; encrypted_api_key: string }[];
    const updateStmt = db.prepare(
      'UPDATE ai_provider_profiles SET encrypted_api_key = ?, updated_at = ? WHERE id = ?'
    );
    const now = new Date().toISOString();

    for (const row of rows) {
      const envSecret = envMapping[row.id];
      if (!envSecret || !envSecret.trim()) continue;
      const currentPlain = decryptSecret(row.encrypted_api_key || '');
      if (!currentPlain || !currentPlain.trim()) {
        updateStmt.run(encryptSecret(envSecret.trim()), now, row.id);
      }
    }
  } catch (err) {
    console.warn('[Database] Failed to backfill profile secrets from env:', err);
  }
}