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[] = [ { 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 = { '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); } }