Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

47.1 KB
Raw Blame
// LLM lập đề xuất ngữ nghĩa (bỏ đoạn nào, nhấn chữ nào, zoom/sfx ở chữ nào, sửa chính tả) → code dựng EDL.
// LLM chỉ quyết Ý NGHĨA theo chỉ số chữ; mọi mốc thời gian, đệm biên cắt, khoảng lặng, mật độ zoom do code (compileEdl).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnClaude, findClaude } from '../generator/claude.mjs';
import { MODEL_IDS } from '../generator/config.mjs';
import { ROOT } from './env.mjs';
import { EDL_VERSION, OUT, REMOVE_REASONS, toOutput, outputDuration, timelineOf, hookDur } from './edl.mjs';
import { compileGraphics, numberHighlights, wordStart } from './graphics.mjs';
import { soundOf, cutAfter, cutBefore, TAIL_Q, LEAD_Q } from './sound.mjs';
import crypto from 'node:crypto';
import { resolveEditStyle, listEditStyleRefs, wrapUntrusted } from '../packs/registry.mjs';
import { lintEditStyle } from '../packs/lint.mjs';

export const STYLES_DIR = path.join(ROOT, 'edit-styles');
const LLM_TIMEOUT_MS = 6 * 60 * 1000;

// ---- thẻ kiểu edit -------------------------------------------------------------------------------------------
/** edit-styles/<id>.md: khối ```---json … ---``` đầu file là preset có version; phần còn lại là hướng dẫn cho LLM.
 *  id = mã tham chiếu: cách dựng gốc ("sach-gon") hoặc mục gói ("tac-gia.goi/slug", qua packs/registry.mjs). */
export function loadStyle(id) {
  const r = resolveEditStyle(id);
  if (!r) throw new Error(`không có kiểu edit "${id}" (có: ${listStyles().join(', ')})`);
  const file = r.file;
  if (r.source !== 'builtin') {
    // cách dựng của gói: preset đã kiểm + kẹp theo schema (L7), phần hướng dẫn bọc như dữ liệu người lạ (L5)
    const lint = lintEditStyle(fs.readFileSync(file), { slug: r.slug });
    if (lint.errors.length) throw new Error(`kiểu edit "${id}" không qua kiểm: ${lint.errors[0]}`);
    return { ...lint.preset, id: r.ref, guide: wrapUntrusted(lint.guide, crypto.randomBytes(8).toString('hex'), 'HƯỚNG DẪN CÁCH DỰNG'), file, source: r.source };
  }
  const text = fs.readFileSync(file, 'utf8');
  const m = /^---json\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/.exec(text.replace(/\r\n/g, '\n'));
  if (!m) throw new Error(`${file}: thiếu khối ---json ở đầu`);
  const preset = JSON.parse(m[1]);
  if (preset.id !== id) throw new Error(`${file}: id trong preset là "${preset.id}"`);
  return { ...preset, guide: m[2].trim(), file };
}
export function listStyles() {
  return listEditStyleRefs();
}

// ---- transcript cho LLM ------------------------------------------------------------------------------------------
const key = (w) => w.toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');

/** Gộp chữ chắc chắn + chữ "không chắc" (nghe lại lần 2) thành 1 dãy đánh số theo thời gian. */
export function wordList(analysis) {
  // p: xác suất whisper cho chữ (chữ nghe lần 2 không có p); why: vì sao chữ đó "không chắc"
  const all = analysis.words.map((w) => ({ w: w.w, s: w.s, e: w.e, unsure: false, p: w.p ?? null }))
    .concat((analysis.unsure || []).map((w) => ({ w: w.w, s: w.s, e: w.e, unsure: true, p: null, why: w.why || '' })));
  all.sort((a, b) => a.s - b.s || a.e - b.e);
  // whisper tách số "50.000" thành "50" + ".000": gộp lại thành một chữ
  const merged = [];
  for (const w of all) {
    const prev = merged[merged.length - 1];
    if (prev && !prev.unsure && !w.unsure && /^[.,]\d{3}/.test(w.w) && /\d$/.test(prev.w)) {
      prev.w += w.w; prev.e = Math.max(prev.e, w.e);
      if (w.p != null) prev.p = prev.p == null ? w.p : Math.min(prev.p, w.p);
    } else merged.push({ ...w });
  }
  return merged.map((w, i) => ({ ...w, i }));
}

function transcriptText(words, exclude = null) {
  const lines = []; let line = []; let skipped = false;
  const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };
  for (let k = 0; k < words.length; k++) {
    const w = words[k];
    if (exclude?.has(w.i)) { if (!skipped) { flush(); lines.push('… (đoạn không dùng cho short, đã bỏ) …'); skipped = true; } continue; }
    skipped = false;
    if (!line.length) line.push(`(${w.s.toFixed(2)}s)`);
    line.push(`[${w.i}]${w.w}${w.unsure ? '?' : ''}`);
    const nx = words[k + 1];
    const gap = nx && !exclude?.has(nx.i) ? nx.s - w.e : 0;
    if (gap >= 0.6) { flush(); lines.push(`… lặng ${gap.toFixed(1)} s …`); }
    else if (/[.?!]$/.test(w.w) || line.length > 16) flush();
  }
  flush();
  return lines.join('\n');
}

/** Phần thêm vào prompt cắt cho kiểu có câu móc / chữ móc / câu trích dẫn (engine đã làm được các trường này). */
function extraFields(style) {
  const f = []; const rules = [];
  if (style.hook?.pullToFront) {
    f.push(`  "hook": {"from": <i>, "to": <i>}`);
    rules.push(`- "hook": câu móc theo thẻ kiểu (chữ đầu..chữ cuối, gồm cả hai đầu), một câu trọn nghĩa, dài ≤ ${style.hook.maxSec} giây theo mốc giây, KHÔNG nằm trong "drop". Code kéo câu này lên đầu bản ra${style.hook.repeatInPlace ? ' rồi phát clip từ đầu (câu vẫn ở chỗ cũ)' : ' và bỏ nó khỏi chỗ cũ'}${style.hook.flash ? ', chèn chớp trắng' : ''}${style.hook.sfx ? ` + "${style.hook.sfx}" (đừng tự thêm "${style.hook.sfx}" vào "sfx")` : ''}. Chọn câu nằm SAU câu mở đầu của phần được giữ (câu đã đứng ngay đầu thì kéo lên là vô nghĩa, nghe 2 lần); chỉ khi không còn câu nào đủ gắt mới chọn câu đầu. Không cần ghi HOOK vào notes.`);
  }
  if (style.hook?.text) {
    f.push(`  "hookText": "<chữ móc ≤ ${style.hook.text.maxChars} ký tự, 1–2 chữ nhấn đặt trong *…*>"`);
    rules.push(`- "hookText": chữ móc to hiện 0–${style.hook.text.until} giây đầu (code vẽ riêng, không phải phụ đề): lợi ích/kết quả của mẹo viết gọn từ chính lời người nói, vd "*3 GIÂY* LÀ XONG". Có chữ móc này thì KHÔNG cần title_card làm chữ móc.`);
  }
  if (style.look?.quote) {
    f.push(`  "quote": {"from": <i>, "to": <i>}`);
    rules.push('- "quote": câu chốt hiện kiểu trích dẫn to giữa khung (code tắt phụ đề thường, làm tối + mờ video): một câu trọn nghĩa 6–25 chữ, không nằm trong "drop", không bỏ chữ nào bên trong. Không cần nhấn (highlights) cả câu, không cần ghi QUOTE vào notes.');
  }
  return { fields: f.length ? ',\n' + f.join(',\n') : '', rules: rules.join('\n') };
}

export function buildPrompt({ words, style, content, names, duration, errors, previous, exclude, extra }) {
  const sfx = style.sfxNames.join(', ');
  const ex = extraFields(style);
  return `Mày là biên tập viên video ngắn tiếng Việt. Video người dùng tự quay, nói trước máy, dài ${duration.toFixed(1)} giây.
Nhiệm vụ: đọc lời chép (có số thứ tự từng chữ) và quyết theo THẺ KIỂU EDIT: bỏ đoạn nào, nhấn chữ nào, zoom và đặt tiếng động ở chữ nào, sửa chữ máy nghe sai.
Chỉ trả về MỘT khối JSON, không giải thích ngoài JSON.

# THẺ KIỂU EDIT: ${style.name} (${style.id})
${style.guide}

# Lời dặn của người dùng
${content?.trim() || '(không có)'}

# Tên riêng / thuật ngữ đúng (người dùng khai)
${namesText(names)}

# Lời chép (máy nghe, có thể sai chính tả; [i] là số thứ tự chữ; chữ có dấu "?" là chữ máy nghe lại lần 2 nhưng không chắc, thường nằm ở chỗ nói lại hoặc nói vấp)
${transcriptText(words, exclude)}

# Định dạng trả về
{
  "drop": [{"from": <i>, "to": <i>, "reason": "retake|false-start|filler|aside", "why": "<ngắn>"}],
  "highlights": [<i>, ...],
  "zooms": [<i>, ...],
  "sfx": [{"word": <i>, "name": "<một trong: ${sfx}>"}],
  "fixes": [{"word": <i>, "text": "<chữ đúng>"}],
  "notes": "<1–2 câu: đã bỏ gì, vì sao>"${ex.fields}
}
Luật:
- "drop" là các khoảng chữ liền nhau [from..to] (gồm cả hai đầu) cần bỏ CẢ TIẾNG LẪN HÌNH. Nói lại: bỏ lần nói trước (kể cả phần nói dở), giữ lần sau cùng. Không chồng nhau. "filler" chỉ dùng cho từ đệm đứng riêng (ờ, ừm, ơ…).
- KHÔNG dùng "drop" để sửa chữ: tên riêng bị máy nghe tách thành 2 chữ (vd "luôn phin") thì giữ tiếng, dùng "fixes": chữ đầu → tên đúng, chữ sau → "" (ẩn khỏi phụ đề).
- Không cần liệt kê khoảng lặng: code tự rút. Không bỏ quá nửa số chữ.
- "highlights", "zooms", "sfx", "fixes" chỉ dùng chữ KHÔNG bị bỏ. Zoom theo mật độ của thẻ kiểu (${style.zoom.perMinute[0]}–${style.zoom.perMinute[1]} lần mỗi phút, cách nhau ≥ ${style.zoom.minGap} giây).
- "fixes" (text "" = ẩn chữ đó khỏi phụ đề, vẫn giữ tiếng): CHỈ sửa chữ mà máy nghe sai rõ ràng: chữ vô nghĩa trong câu, hoặc tên riêng/thuật ngữ người dùng đã dặn. Chữ đang hợp nghĩa (dù mày nghĩ người nói muốn chữ khác) thì GIỮ NGUYÊN — sửa sai còn tệ hơn không sửa. Mỗi mục 1 chữ → 1 chữ đúng (có thể vài tiếng).
${ex.rules ? ex.rules + '\n' : ''}${extra ? `\n# YÊU CẦU THÊM\n${extra}\n` : ''}${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
}

export const parseNames = (names) => (Array.isArray(names) ? names : String(names || '').split(/[,;\n]/))
  .map((x) => String(x).trim()).filter(Boolean).slice(0, 40);
function namesText(names) {
  const list = parseNames(names);
  return list.length ? list.map((x) => '- ' + x).join('\n') + '\nChữ máy nghe gần giống các tên này thì sửa thành đúng tên. Ngoài các tên này, chỉ sửa chữ vô nghĩa rõ ràng.'
    : '(không có) — đừng tự đoán tên riêng.';
}

// ---- gọi Claude (không tool) -----------------------------------------------------------------------------------
export function callClaude(prompt, { model = process.env.EDIT_MODEL || MODEL_IDS.sonnet, log = console.log } = {}) {
  if (!findClaude()) return Promise.reject(new Error('Không tìm thấy lệnh claude (cài Claude Code hoặc đặt CLAUDE_BIN)'));
  const args = ['-p', '--output-format', 'json', '--permission-mode', 'default', '--tools', '',
    '--setting-sources', 'project', '--strict-mcp-config', '--no-session-persistence', '--max-turns', '2', '--model', model];
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-edit-'));
  log(`LLM: ${model}`);
  return new Promise((resolve, reject) => {
    const p = spawnClaude(args, { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });
    let out = ''; let err = '';
    const timer = setTimeout(() => { p.kill(); reject(new Error(`Claude quá ${LLM_TIMEOUT_MS / 1000}s`)); }, LLM_TIMEOUT_MS);
    p.stdout.on('data', (d) => { out += d; });
    p.stderr.on('data', (d) => { err += d; });
    p.on('error', (e) => { clearTimeout(timer); reject(new Error('spawn claude lỗi: ' + e.message)); });
    p.on('close', (code) => {
      clearTimeout(timer);
      fs.rm(cwd, { recursive: true, force: true }, () => {});
      let r = null;
      try { r = JSON.parse(out.trim().split(/\r?\n/).pop()); } catch { /* không phải JSON */ }
      if (code !== 0 || !r || r.is_error) return reject(new Error(`claude thoát mã ${code}: ${(r?.result || err || out).toString().trim().slice(-500)}`));
      resolve({ text: String(r.result || ''), costUSD: r.total_cost_usd ?? null, usage: r.usage || {} });
    });
    p.stdin.end(prompt);
  });
}

export function parseProposal(text) {
  const m = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
  const raw = (m ? m[1] : text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)).trim();
  return JSON.parse(raw);
}

// ---- kiểm đề xuất (ngữ nghĩa) -----------------------------------------------------------------------------------
/** Trả {errors[], clean}: clean là đề xuất đã bỏ mục hỏng (dùng khi LLM sửa 1 vòng vẫn sai). */
export function checkProposal(p, words, style, exclude = null) {
  const errors = []; const n = words.length;
  const ex = exclude || new Set();
  const isIdx = (i) => Number.isInteger(i) && i >= 0 && i < n;
  const clean = { drop: [], highlights: [], zooms: [], sfx: [], fixes: [], notes: typeof p?.notes === 'string' ? p.notes : '' };
  if (!p || typeof p !== 'object') return { errors: ['không phải object JSON'], clean };
  const dropped = new Set();
  const drops = Array.isArray(p.drop) ? [...p.drop].sort((a, b) => a.from - b.from) : [];
  if (p.drop !== undefined && !Array.isArray(p.drop)) errors.push('"drop" phải là mảng');
  let lastTo = -1;
  for (const d of drops) {
    if (!isIdx(d.from) || !isIdx(d.to) || d.from > d.to) { errors.push(`drop ${JSON.stringify(d)}: from/to không hợp lệ (0..${n - 1}, from ≤ to)`); continue; }
    if (d.from <= lastTo) { errors.push(`drop ${d.from}–${d.to} chồng lên khoảng trước`); continue; }
    if (ex.has(d.from) || ex.has(d.to)) { errors.push(`drop ${d.from}–${d.to}: nằm ngoài đoạn đã chọn cho short (đã bỏ sẵn)`); continue; }
    const reason = ['retake', 'false-start', 'filler', 'aside'].includes(d.reason) ? d.reason : 'retake';
    if (reason !== d.reason) errors.push(`drop ${d.from}–${d.to}: reason "${d.reason}" không hợp lệ`);
    if (reason === 'filler') {
      const notFiller = words.slice(d.from, d.to + 1).filter((w) => !style.hesitations.has(key(w.w)));
      if (notFiller.length) { errors.push(`drop ${d.from}–${d.to} (filler): "${notFiller.map((w) => w.w).join(' ')}" không phải từ đệm; sửa chữ thì dùng fixes`); continue; }
    }
    clean.drop.push({ from: d.from, to: d.to, reason, why: String(d.why || '') });
    for (let i = d.from; i <= d.to; i++) dropped.add(i);
    lastTo = d.to;
  }
  const live = n - ex.size;
  const sure = words.filter((w) => !w.unsure && !ex.has(w.i)).length;
  if (dropped.size > Math.max(3, 0.5 * live)) errors.push(`bỏ ${dropped.size}/${live} chữ, quá nửa`);
  if (sure && words.filter((w) => !w.unsure && !dropped.has(w.i) && !ex.has(w.i)).length === 0) errors.push('không còn chữ nào được giữ');
  const keptIdx = (i, what) => {
    if (!isIdx(i)) { errors.push(`${what} ${i}: không có chữ này`); return false; }
    if (dropped.has(i) || ex.has(i)) { errors.push(`${what} ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return false; }
    return true;
  };
  for (const i of p.highlights || []) if (keptIdx(i, 'highlight')) clean.highlights.push(i);
  for (const i of p.zooms || []) if (keptIdx(i, 'zoom')) clean.zooms.push(i);
  for (const s of p.sfx || []) {
    if (!style.sfxNames.includes(s?.name)) { errors.push(`sfx "${s?.name}" không có trong danh sách`); continue; }
    if (keptIdx(s.word, 'sfx')) clean.sfx.push({ word: s.word, name: s.name });
  }
  for (const f of p.fixes || []) {
    const t = typeof f?.text === 'string' ? f.text.trim() : '';
    if (typeof f?.text !== 'string' || t.length > 40) { errors.push(`fix ${JSON.stringify(f)}: chữ sửa không hợp lệ hoặc quá dài`); continue; }
    if (keptIdx(f.word, 'fix')) clean.fixes.push({ word: f.word, text: t });
  }
  // câu móc / câu trích dẫn: LLM trả trường riêng; bản guidance cũ ghi "HOOK: [i]–[j]" / "QUOTE: [i]–[j]" vào notes
  const spanOf = (field, tag) => {
    if (p[field] && typeof p[field] === 'object') return p[field];
    const m = new RegExp(String.raw`${tag}\s*:?\s*\[?(\d+)\]?\s*[–—-]+\s*\[?(\d+)\]?`, 'i').exec(clean.notes);
    return m ? { from: Number(m[1]), to: Number(m[2]) } : null;
  };
  const checkSpan = (sp, what, maxSec) => {
    if (!isIdx(sp?.from) || !isIdx(sp?.to) || sp.from > sp.to) { errors.push(`${what} ${JSON.stringify(sp)}: from/to không hợp lệ (0..${n - 1}, from ≤ to)`); return null; }
    for (let i = sp.from; i <= sp.to; i++) if (dropped.has(i) || ex.has(i)) { errors.push(`${what} ${sp.from}–${sp.to}: chữ ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return null; }
    const sec = words[sp.to].e - words[sp.from].s;
    if (maxSec && sec > maxSec + 1e-6) { errors.push(`${what} ${sp.from}–${sp.to} dài ${sec.toFixed(1)} s, quá ${maxSec} s: chọn câu ngắn hơn`); return null; }
    return { from: sp.from, to: sp.to };
  };
  if (style.hook?.pullToFront) {
    const sp = spanOf('hook', 'HOOK');
    if (sp) clean.hook = checkSpan(sp, 'hook', style.hook.maxSec);
    else errors.push('thiếu "hook" (câu móc kéo lên đầu)');
  }
  if (style.look?.quote) {
    const sp = spanOf('quote', 'QUOTE');
    if (sp) clean.quote = checkSpan(sp, 'quote', null);
    else errors.push('thiếu "quote" (câu chốt hiện kiểu trích dẫn)');
  }
  if (style.hook?.text) {
    const t = typeof p.hookText === 'string' ? p.hookText.trim() : '';
    const plain = t.replace(/\*/g, '');
    if (!plain) errors.push('thiếu "hookText" (chữ móc 0–2 giây)');
    else if ([...plain].length > style.hook.text.maxChars) errors.push(`hookText "${plain}" dài quá ${style.hook.text.maxChars} ký tự`);
    else clean.hookText = t;
  }
  return { errors, clean };
}

/** Kiểu có trần độ dài (maxSec): bản ra dài quá → lời yêu cầu LLM bỏ thêm; không quá → null. */
export function maxSecRequest(style, outSec) {
  if (!style.maxSec || outSec <= style.maxSec + 1e-6) return null;
  const need = Math.ceil((outSec - style.maxSec) * 10) / 10;
  const vi = (x) => x.toFixed(1).replace('.', ',');
  return `Bản ra theo đề xuất trước dài ${vi(outSec)} giây, quá trần ${style.maxSec} giây của kiểu này. Bỏ thêm ≥ ${vi(need)} giây lời (drop thêm câu giải thích, câu phụ; giữ câu móc, các bước làm, con số và câu kết quả). Trả lại đề xuất ĐẦY ĐỦ.`;
}

/** Đề xuất khi không dùng LLM (--llm off, hoặc LLM lỗi): không bỏ chữ nào, zoom đều theo mật độ thẻ kiểu. */
export function fallbackProposal(words, style, exclude = null) {
  const zooms = []; let last = -Infinity;
  const gap = Math.max(style.zoom.minGap, 60 / style.zoom.perMinute[0] / 1.5);
  for (const w of words) {
    if (w.unsure || key(w.w).length < 3 || exclude?.has(w.i)) continue;
    if (w.s - last >= gap) { zooms.push(w.i); last = w.s; }
  }
  return { drop: [], highlights: [], zooms, sfx: [], fixes: [], notes: 'không dùng LLM: chỉ rút khoảng lặng, zoom đều' };
}

/** LLM lập đề xuất; sai thì gửi lỗi cho LLM sửa đúng 1 vòng; vẫn sai thì bỏ mục hỏng. */
export async function propose({ words, style, content, names, duration, llm = 'on', log = console.log, exclude = null, extra = '' }) {
  if (llm === 'off') return { proposal: fallbackProposal(words, style, exclude), rounds: 0, warnings: ['LLM tắt'], costUSD: 0 };
  const warnings = [];
  let text = ''; let cost = 0; let prev = null;
  for (let round = 1; round <= 2; round++) {
    const prompt = buildPrompt({ words, style, content, names, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '', exclude, extra });
    let checked;
    try {
      const r = await callClaude(prompt, { log });
      text = r.text; cost += r.costUSD || 0;
      checked = checkProposal(parseProposal(text), words, style, exclude);
    } catch (e) {
      checked = { errors: [`không đọc được JSON: ${e.message}`], clean: null };
    }
    if (!checked.errors.length) return { proposal: checked.clean, rounds: round, warnings, costUSD: cost, raw: text };
    log(`LLM vòng ${round}: ${checked.errors.length} lỗi: ${checked.errors.slice(0, 3).join('; ')}`);
    prev = checked;
  }
  warnings.push(...prev.errors.map((e) => 'bỏ mục hỏng: ' + e));
  return { proposal: prev.clean || fallbackProposal(words, style, exclude), rounds: 2, warnings, costUSD: cost, raw: text };
}

// ---- code dựng EDL từ đề xuất ------------------------------------------------------------------------------------
const LEAD = 0.10;      // giữ trước chữ đầu mỗi đoạn
const TAIL = 0.22;      // giữ sau chữ cuối (whisper hay báo hết chữ sớm ~0,15 s; spike đo 0,10–0,21 s)
const MIN_CUT = 0.12;   // cắt ngắn hơn thế thì không đáng một cú nhảy hình
const EDGE_END = 0.35;  // giữ sau chữ cuối cùng của video
const HOOK_AT_START = 1.0; // câu móc bắt đầu trong ngần này giây đầu bản ra thì coi như đã ở đầu, không kéo

/**
 * Một khoảng bỏ (của LLM hoặc từ đệm) chỉ được bỏ khi ở mỗi mép chạm chữ giữ, giọng có ngắt thật (khoảng lặng hoặc
 * trũng hẳn). Nói liền một mạch sang chữ giữ thì gần như chắc đó là một phần của cùng một từ/con số mà whisper tách
 * hoặc nghe 2 lần ("Năm 0" + "5070T" = một lần đọc "5070 Ti"): bỏ nó là cắt vào giữa từ. Trả lý do từ chối hoặc null.
 */
export function dropEdgeProblem(snd, words, from, to, isRemoved) {
  if (!snd.env && !snd.quiet.length) return null;
  const span = words.slice(from, to + 1);
  const s0 = Math.min(...span.map((w) => w.s)); const e1 = Math.max(...span.map((w) => w.e));
  const prev = from > 0 && !isRemoved(from - 1) ? words[from - 1] : null;
  const next = to + 1 < words.length && !isRemoved(to + 1) ? words[to + 1] : null;
  if (prev && prev.e > s0 - 0.6 && !snd.hasBreak(Math.min(prev.e, s0) - 0.05, Math.max(prev.e, s0) + 0.08)) return `nói liền với "${prev.w}" trước nó, không có chỗ ngắt`;
  if (next && next.s < e1 + 0.6 && !snd.hasBreak(Math.min(e1, next.s) - 0.08, Math.max(e1, next.s) + 0.05)) return `nói liền sang "${next.w}" sau nó, không có chỗ ngắt`;
  return null;
}

/** Hợp các khoảng [start, end] (sắp theo thời gian, gộp chỗ chạm nhau). */
function unionSpans(spans) {
  const s = spans.filter((x) => x.end - x.start > 1e-3).map((x) => ({ start: x.start, end: x.end })).sort((a, b) => a.start - b.start);
  const out = [];
  for (const x of s) {
    const last = out[out.length - 1];
    if (last && x.start <= last.end + 1e-3) last.end = Math.max(last.end, x.end);
    else out.push({ ...x });
  }
  return out;
}

/**
 * restore: [{start, end}] giây nguồn phải giữ lại dù đã bị bỏ (sửa lẹm chữ sau khi nghe lại bản cắt, repairCuts).
 * Trả EDL (+ _warnings nội bộ: khoảng bỏ bị từ chối vì nói liền, đồ hoạ bỏ…).
 */
export function compileEdl({ id, ingestRes, analysis, words, proposal, style, music, draft, exclude = [], graphics = null, restore = [] }) {
  const dur = ingestRes.source.duration;
  const hes = new Set(analysis.hesitations || []);
  const snd = soundOf(analysis);
  const cutWarnings = [];
  const reasonOf = new Map();
  for (const i of exclude) reasonOf.set(i, 'trim');
  const removedNow = (i) => reasonOf.has(i);
  for (const d of proposal.drop) {
    const why = dropEdgeProblem(snd, words, d.from, d.to, removedNow);
    if (why) { cutWarnings.push(`không bỏ "${words.slice(d.from, d.to + 1).map((w) => w.w).join(' ')}" (${d.reason}): ${why}, có thể là một phần của từ/số`); continue; }
    for (let i = d.from; i <= d.to; i++) reasonOf.set(i, d.reason);
  }
  for (const w of words) {
    if (!style.cutFillers || !hes.has(key(w.w)) || reasonOf.has(w.i)) continue;
    if (dropEdgeProblem(snd, words, w.i, w.i, removedNow)) continue; // "ờ" nói lướt liền chữ khác: để nguyên
    reasonOf.set(w.i, 'filler');
  }
  const kept = words.filter((w) => !reasonOf.has(w.i));
  if (!kept.length) throw new Error('không còn chữ nào để giữ');
  let keep = []; let removed = [];
  const before0 = words.filter((w) => w.i < kept[0].i);
  const first = cutBefore(snd, kept[0], before0.length ? Math.max(...before0.map((w) => w.e)) : kept[0].s - 0.6, before0.length ? Math.max(...before0.map((w) => w.s)) : 0);
  let segStart = Math.max(0, first ?? kept[0].s - LEAD);
  if (segStart > 0.3) removed.push({ start: 0, end: +segStart.toFixed(3), reason: 'edge', words: words.filter((w) => w.e <= segStart).map((w) => w.w).join(' ') });
  for (let k = 0; k + 1 < kept.length; k++) {
    const a = kept[k]; const b = kept[k + 1];
    const between = words.filter((w) => w.i > a.i && w.i < b.i);
    const gap = b.s - a.e;
    if (!between.length && gap <= style.pause) continue;
    let cs = a.e + TAIL; let ce = b.s - LEAD;
    if (between.length) {
      // whisper xếp chữ theo lúc bắt đầu; chữ bỏ cuối cùng có khi kết thúc muộn hơn chữ đứng sau nó
      const f = between[0]; const lEnd = Math.max(...between.map((w) => w.e)); const lS = Math.max(...between.map((w) => w.s));
      cs = Math.max(a.e + 0.04, Math.min(cs, f.s - 0.005));
      ce = Math.min(b.s - 0.04, Math.max(ce, lEnd + 0.005));
      const sa = cutAfter(snd, a, f.s, f.e); const sb = cutBefore(snd, b, lEnd, lS);
      if (sa != null) cs = Math.max(segStart + 0.04, sa);
      if (sb != null) ce = Math.min(b.e - 0.02, sb);
    } else if (snd.env) {
      // khoảng hở giữa 2 chữ giữ: rút theo khoảng lặng thật; whisper báo hở mà giọng không tắt thì không cắt
      const q = snd.quietTouching(a.e - 0.06, b.s + 0.06);
      if (!q) continue;
      cs = Math.max(a.e - 0.06, Math.min(Math.max(q.q0, a.s + 0.02) + TAIL_Q, q.q1));
      ce = Math.min(b.s + 0.06, Math.max(Math.min(q.q1, b.e - 0.02) - LEAD_Q, q.q0));
      // kiểu kể chuyện/vlog: khoảng ngừng dài còn lại ≈ pauseKeep (mỗi bên một nửa), vẫn nằm trong khoảng lặng thật
      if (style.pauseKeep) { cs = Math.min(q.q1, Math.max(cs, a.e + style.pauseKeep / 2)); ce = Math.max(q.q0, Math.min(ce, b.s - style.pauseKeep / 2)); }
    } else if (style.pauseKeep) {
      cs = a.e + Math.max(TAIL, style.pauseKeep / 2); ce = b.s - Math.max(LEAD, style.pauseKeep / 2);
    }
    if (ce - cs < MIN_CUT) continue;
    keep.push({ start: +segStart.toFixed(3), end: +cs.toFixed(3) });
    const reasons = [...new Set(between.map((w) => reasonOf.get(w.i)).filter(Boolean))];
    removed.push({ start: +cs.toFixed(3), end: +ce.toFixed(3), reason: reasons[0] || 'pause', words: between.map((w) => w.w).join(' ') });
    segStart = ce;
  }
  const last = kept[kept.length - 1];
  const endQ = snd.quietTouching(last.e - 0.06, last.e + 0.6);
  const endT = Math.min(dur, Math.max(last.e + EDGE_END, endQ ? Math.min(endQ.q0 + EDGE_END, endQ.q1) : 0));
  keep.push({ start: +segStart.toFixed(3), end: +endT.toFixed(3) });
  if (dur - endT > 0.3) removed.push({ start: +endT.toFixed(3), end: +dur.toFixed(3), reason: 'edge', words: '' });
  // giữ lại các khoảng sửa lẹm chữ: hợp vào keep, trừ khỏi removed; chữ chắc trong đó lên lại phụ đề
  const restored = unionSpans((restore || []).map((r) => ({ start: Math.max(0, r.start), end: Math.min(dur, r.end) })));
  if (restored.length) {
    keep = unionSpans([...keep, ...restored]).map((k) => ({ start: +k.start.toFixed(3), end: +k.end.toFixed(3) }));
    removed = removed.flatMap((r) => {
      let parts = [{ ...r }];
      for (const x of restored) parts = parts.flatMap((p) => (x.end <= p.start || x.start >= p.end ? [p] : [{ ...p, end: x.start }, { ...p, start: x.end }].filter((q) => q.end - q.start >= 0.01)));
      return parts.map((p) => ({ ...p, start: +p.start.toFixed(3), end: +p.end.toFixed(3) }));
    });
    for (const w of words) {
      const mid = (w.s + w.e) / 2;
      if (reasonOf.has(w.i) && !w.unsure && restored.some((x) => mid >= x.start && mid <= x.end)) reasonOf.delete(w.i);
    }
  }
  const byIdx = new Map(words.map((w) => [w.i, w]));
  // câu móc kéo lên đầu: bản ra = [hook] + keep. Mép cắt như mọi đoạn giữ (vào khoảng lặng/chỗ trũng, không lẹm chữ).
  let hook = null;
  const hp = style.hook?.pullToFront ? proposal.hook : null;
  if (hp && byIdx.has(hp.from) && byIdx.has(hp.to)) {
    const wf = byIdx.get(hp.from); const wt = byIdx.get(hp.to);
    const prev = byIdx.get(hp.from - 1); const next = byIdx.get(hp.to + 1);
    let hs = cutBefore(snd, wf, prev ? prev.e : wf.s - 0.6, prev ? prev.s : 0) ?? wf.s - LEAD;
    let he = cutAfter(snd, wt, next ? next.s : wt.e + 0.6, next ? next.e : dur) ?? wt.e + TAIL;
    if (prev && prev.e <= wf.s) hs = Math.max(hs, prev.e + 0.01);
    if (next && next.s >= wt.e) he = Math.min(he, next.s - 0.01);
    hs = Math.max(0, Math.min(hs, wf.s - 0.02)); he = Math.min(dur, Math.max(he, wt.e + 0.05));
    // câu móc vốn đã ở đầu bản ra (vd đoạn chọn mở bằng chính câu đó): không kéo nữa, nếu không sẽ nghe 2 lần liền nhau;
    // tiếng của câu móc vẫn đặt ở chữ cuối câu
    const at0 = toOutput(keep, Math.max(hs, keep[0].start));
    if (at0 !== null && at0 <= HOOK_AT_START) {
      if (style.hook.sfx) proposal = { ...proposal, sfx: [...proposal.sfx, { word: hp.to, name: style.hook.sfx }] };
      cutWarnings.push(`câu móc "${words.slice(hp.from, hp.to + 1).map((x) => x.w).join(' ')}" đã ở đầu clip (${at0.toFixed(1)} s): không kéo lên`);
    } else if (he - hs > 6) cutWarnings.push(`câu móc ${hp.from}–${hp.to} dài ${(he - hs).toFixed(1)} s (> 6 s), không kéo lên đầu`);
    else {
      const repeat = style.hook.repeatInPlace !== false;
      hook = { start: +hs.toFixed(3), end: +he.toFixed(3), repeat, flash: !!style.hook.flash,
        sfx: style.hook.sfx ? { name: style.hook.sfx, at: +wt.s.toFixed(3), gainDb: style.sfx.gainDb } : null };
      if (!repeat) {
        // không lặp lại: trừ khoảng móc khỏi keep (chữ trong đó vẫn lên phụ đề, ở đầu bản ra)
        keep = keep.flatMap((k) => (hook.end <= k.start || hook.start >= k.end ? [k]
          : [{ start: k.start, end: hook.start }, { start: hook.end, end: k.end }].filter((x) => x.end - x.start >= 1 / 30)));
      }
    }
  }
  const inHookT = (t) => !!hook && t >= hook.start - 1e-6 && t <= hook.end + 1e-6;
  const inKeepT = (t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6) || inHookT(t);
  const keptAll = words.filter((w) => !reasonOf.has(w.i) && inKeepT((w.s + w.e) / 2));
  if (!keep.length) throw new Error('câu móc chiếm hết đoạn giữ');
  const tlKeep = hook ? [...keep, { start: hook.start, end: hook.end }] : keep; // mốc chữ: kẹp vào đoạn giữ (hoặc câu móc)

  // zoom: theo đề xuất, ép khoảng cách tối thiểu của thẻ kiểu
  const zooms = []; let lastZ = -Infinity;
  for (const i of [...new Set(proposal.zooms)].sort((x, y) => x - y)) {
    const w = byIdx.get(i);
    if (!w || reasonOf.has(i) || w.s - lastZ < style.zoom.minGap) continue;
    zooms.push({ at: +wordStart(tlKeep, w).toFixed(3), dur: style.zoom.dur, scale: style.zoom.scale, kind: style.zoom.kind, word: i });
    lastZ = w.s;
  }
  // đồ hoạ (kiểu có style.graphics): giây nguồn theo keep, zoom nhẹ + sfx khi vào; zoom của LLM gần đó nhường chỗ
  let gfx = { graphics: [], zooms: [], sfx: [], warnings: [] };
  if (style.graphics && graphics?.length) {
    gfx = compileGraphics({ plan: graphics, words, keep: timelineOf({ keep, hook }), style });
    const near = (t) => gfx.zooms.some((g) => t > g.at - style.zoom.minGap && t < g.at + g.dur + style.zoom.minGap / 2);
    const merged = zooms.filter((z) => !near(z.at)).concat(gfx.zooms).sort((a, b) => a.at - b.at);
    zooms.length = 0; zooms.push(...merged);
  }
  // zoom không được tràn sang cú sau
  for (let k = 0; k + 1 < zooms.length; k++) zooms[k].dur = +Math.max(0.2, Math.min(zooms[k].dur, zooms[k + 1].at - zooms[k].at - 0.05)).toFixed(3);

  const fixes = new Map(proposal.fixes.map((f) => [f.word, f.text]));
  const capWords = keptAll.filter((w) => !hes.has(key(w.w)) && fixes.get(w.i) !== '')
    .map((w) => ({ i: w.i, w: fixes.get(w.i) || w.w, start: +w.s.toFixed(3), end: +Math.max(w.e, w.s + 0.05).toFixed(3) }));
  const capIds = new Set(capWords.map((w) => w.i));
  const numHi = style.captions.numbers ? numberHighlights(capWords) : [];

  const sfx = [];
  for (const s of proposal.sfx) { const w = byIdx.get(s.word); if (w && !reasonOf.has(s.word)) sfx.push({ at: +wordStart(tlKeep, w).toFixed(3), name: s.name, gainDb: style.sfx.gainDb }); }
  if (style.sfx.onZoom) for (const z of zooms) sfx.push({ at: z.at, name: style.sfx.onZoom, gainDb: style.sfx.gainDb });
  sfx.push(...gfx.sfx);
  sfx.sort((a, b) => a.at - b.at);
  const sfxOut = sfx.filter((s, k) => k === 0 || s.at - sfx[k - 1].at > 0.15).slice(0, style.sfx.max);

  return {
    version: EDL_VERSION, id, createdAt: new Date().toISOString(), style: style.id,
    source: ingestRes.source, proxy: ingestRes.proxy,
    output: { ...OUT },
    keep, removed: removed.filter((r) => REMOVE_REASONS.includes(r.reason)),
    reframe: { mode: 'face' },
    zooms,
    captions: {
      style: style.captions.style, renderer: draft ? 'pil' : 'hyperframes', maxWords: style.captions.maxWords,
      position: style.captions.position, words: capWords, highlights: [...new Set([...proposal.highlights, ...numHi])].filter((i) => capIds.has(i)).sort((a, b) => a - b),
    },
    sfx: sfxOut,
    graphics: gfx.graphics,
    hook,
    hookText: style.hook?.text && proposal.hookText ? { text: proposal.hookText, until: style.hook.text.until } : null,
    quote: style.look?.quote && proposal.quote && byIdx.has(proposal.quote.from) && byIdx.has(proposal.quote.to)
      ? { start: +byIdx.get(proposal.quote.from).s.toFixed(3), end: +byIdx.get(proposal.quote.to).e.toFixed(3), dimTo: style.look.quote.dimTo, blurPx: style.look.quote.blurPx, dimIn: style.look.quote.dimIn }
      : null,
    music: music ? { file: path.resolve(music), gainDb: style.music.gainDb, duckDb: style.music.duckDb, fadeOut: style.music.fadeOut } : null,
    audio: { crossfadeMs: 20, keepSourceAudio: true },
    notes: proposal.notes || '',
    ...(gfx.warnings.length || cutWarnings.length ? { _warnings: [...cutWarnings, ...gfx.warnings] } : {}),
  };
}

// ---- sửa bằng lời (revise) ------------------------------------------------------------------------------------
// Người dùng nói "bỏ đoạn 12s", "zoom ít lại", "bỏ 3 giây đầu"… → LLM trả: đề xuất mới (cùng dạng propose),
// các khoảng cần cắt theo GIÂY CỦA VIDEO HIỆN TẠI, và vài núm chỉnh kiểu. Code đổi giây bản ra → giây nguồn (theo keep
// hiện tại), nới mép cắt cho trọn chữ, dựng lại EDL. KHÔNG phân tích lại video.

// ---- sửa lẹm chữ sau khi nghe lại bản cắt -----------------------------------------------------------------------
const RESTORE_MAX = 2.5; // khoảng bỏ ngắn hơn thế (nói lại, nói dở, lặng) mà làm lẹm chữ thì giữ lại cả khoảng
const NO_RESTORE = new Set(['trim', 'edge', 'by-hand']);
const PHRASE = 1.6;      // nới mép đoạn dài: tìm chỗ người nói ngừng trong ngần này giây
/**
 * overcut: kết quả "nghe lại bản cắt" của lumedit render ({lost, chopped}: chữ, giây bản ra, vết nối). Mỗi chữ mất/lẹm
 * ở một vết nối: khoảng bỏ ngắn (nói lại, nói dở, lặng) → giữ lại cả khoảng (whisper đã gán nhầm chỗ chữ); khoảng dài
 * (ngoài đoạn chọn, cắt tay) → nới mép phía chữ bị lẹm tới chỗ giọng ngắt kế tiếp (≤ 0,5 s).
 * Trả [{start, end, why}] giây nguồn để compileEdl giữ lại (restore).
 */
export function repairCuts(edl, overcut, analysis) {
  const snd = soundOf(analysis);
  const keep = edl.keep; const out = [];
  const ends = []; let acc = edl.hook ? edl.hook.end - edl.hook.start : 0; // vết nối móc → clip không tính
  for (const k of keep) { acc += k.end - k.start; ends.push(acc); }
  for (const item of [...(overcut?.lost || []), ...(overcut?.chopped || [])]) {
    if (typeof item.join !== 'number') continue;
    let k = -1; let bd = 0.06;
    ends.forEach((e, j) => { if (Math.abs(e - item.join) < bd) { bd = Math.abs(e - item.join); k = j; } });
    if (k < 0 || k + 1 >= keep.length) continue;
    const g0 = keep[k].end; const g1 = keep[k + 1].start;
    const inGap = (edl.removed || []).filter((r) => r.start < g1 - 1e-3 && r.end > g0 + 1e-3);
    const why = `"${item.word}" lẹm ở vết nối ${item.join.toFixed(2)} s${item.heard_as ? ` (nghe lại thành "${item.heard_as}")` : ''}`;
    if (g1 - g0 <= RESTORE_MAX && !inGap.some((r) => NO_RESTORE.has(r.reason))) { out.push({ start: g0, end: g1, why: `${why}: giữ lại ${g0.toFixed(2)}–${g1.toFixed(2)} s nguồn` }); continue; }
    // Mép đoạn chọn rơi giữa câu nói liền: nới tới chỗ người nói thật sự ngừng (khoảng lặng ≥ 0,15 s, trong 1,6 s) để
    // trọn cụm; không có chỗ ngừng thì nới tới ngay trước chữ kế tiếp (không kéo chữ đó vào nửa chừng).
    const heardW = analysis?.words || [];
    const pauses = snd.quiet.filter(([a, b]) => b - a >= 0.15);
    if (item.at < item.join - 1e-3) {
      const p = pauses.find(([a]) => a > g0 + 0.02 && a < g0 + PHRASE && a < g1);
      if (p) { const to = Math.min(p[0] + TAIL_Q, p[1]); out.push({ start: g0, end: Math.min(to, g1), why: `${why}: nới cuối đoạn tới chỗ ngừng ${g0.toFixed(2)} → ${to.toFixed(2)} s nguồn` }); continue; }
      // chữ bị lẹm (giây nguồn) → chữ ngay sau nó: nới tới trước chữ đó
      const src = g0 - (item.join - item.at);
      const me = heardW.reduce((b, w) => (Math.abs(w.s - src) < Math.abs((b?.s ?? Infinity) - src) ? w : b), null);
      const nx = heardW.find((w) => w.s > Math.max(g0 + 0.02, (me?.s ?? g0) + 0.02) && w !== me);
      const lim = Math.min(g0 + 0.5, nx ? nx.s + 0.03 : Infinity);
      const q = snd.quietTouching(g0, lim);
      const to = q ? Math.min(Math.max(q.q0, g0) + TAIL_Q, q.q1, lim) : snd.env ? snd.quietest(g0 + 0.06, Math.max(g0 + 0.08, lim), true) : Math.min(g0 + 0.2, lim);
      if (to > g0 + 0.01) out.push({ start: g0, end: Math.min(to, g1), why: `${why}: nới cuối đoạn ${g0.toFixed(2)} → ${to.toFixed(2)} s nguồn` });
    } else {
      const p = [...pauses].reverse().find(([, b]) => b < g1 - 0.02 && b > g1 - PHRASE && b > g0);
      if (p) { const from = Math.max(p[1] - LEAD_Q, p[0]); out.push({ start: Math.max(from, g0), end: g1, why: `${why}: nới đầu đoạn từ chỗ ngừng ${g1.toFixed(2)} → ${from.toFixed(2)} s nguồn` }); continue; }
      const src = g1 + (item.at - item.join);
      const me = heardW.reduce((b, w) => (Math.abs(w.s - src) < Math.abs((b?.s ?? Infinity) - src) ? w : b), null);
      const pv = [...heardW].reverse().find((w) => w.e < Math.min(g1 - 0.02, (me?.e ?? g1) - 0.02) && w !== me && w.s < (me?.s ?? g1));
      const lim = Math.max(g1 - 0.5, pv ? pv.e - 0.03 : -Infinity);
      const q = snd.quietTouching(lim, g1);
      const from = q ? Math.max(Math.min(q.q1, g1) - LEAD_Q, q.q0, lim) : snd.env ? snd.quietest(Math.min(g1 - 0.08, lim), g1 - 0.06, false) : Math.max(g1 - 0.2, lim);
      if (from < g1 - 0.01) out.push({ start: Math.max(from, g0), end: g1, why: `${why}: nới đầu đoạn ${g1.toFixed(2)} → ${from.toFixed(2)} s nguồn` });
    }
  }
  const seen = new Set();
  return out.map((r) => ({ start: +r.start.toFixed(3), end: +r.end.toFixed(3), why: r.why }))
    .filter((r) => { const k = `${r.start}-${r.end}`; if (seen.has(k)) return false; seen.add(k); return true; });
}

/** Khoảng giây bản ra [a,b) → các khoảng giây nguồn (trong keep); mép rơi giữa chữ thì nới ra trọn chữ. */
export function outputCutToSource(keep, a, b, words) {
  const res = [];
  let acc = hookDur(keep); // keep có .hook (timelineOf): giây bản ra của keep bắt đầu sau câu móc
  for (const k of keep) {
    const d = k.end - k.start;
    const lo = Math.max(a, acc); const hi = Math.min(b, acc + d);
    if (hi > lo) res.push({ start: k.start + (lo - acc), end: k.start + (hi - acc) });
    acc += d;
  }
  for (const c of res) {
    for (const w of words) {
      if (w.s < c.start && w.e > c.start) c.start = Math.max(0, w.s - 0.02);
      if (w.s < c.end && w.e > c.end) c.end = w.e + 0.02;
    }
  }
  return res;
}

/** Trừ các khoảng nguồn khỏi EDL (keep), lọc phụ đề/zoom/sfx rơi vào chỗ bỏ. */
export function applyExtraCuts(edl, cuts) {
  if (!cuts?.length) return edl;
  let keep = edl.keep.map((k) => ({ ...k }));
  for (const c of cuts) {
    const next = [];
    for (const k of keep) {
      if (c.end <= k.start || c.start >= k.end) { next.push(k); continue; }
      if (c.start > k.start) next.push({ start: k.start, end: +c.start.toFixed(3) });
      if (c.end < k.end) next.push({ start: +c.end.toFixed(3), end: k.end });
    }
    keep = next.filter((k) => k.end - k.start >= 1 / 30);
  }
  const inK = (t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);
  const words = edl.captions.words.filter((w) => inK((w.start + w.end) / 2));
  const ids = new Set(words.map((w) => w.i));
  return {
    ...edl, keep,
    removed: [...edl.removed, ...cuts.map((c) => ({ start: +c.start.toFixed(3), end: +c.end.toFixed(3), reason: 'by-hand', words: '' }))].sort((x, y) => x.start - y.start),
    zooms: edl.zooms.filter((z) => inK(z.at)),
    sfx: edl.sfx.filter((x) => inK(x.at)),
    captions: { ...edl.captions, words, highlights: edl.captions.highlights.filter((i) => ids.has(i)) },
  };
}

/** Núm chỉnh kiểu mà lời sửa được phép đổi (kẹp vào khoảng an toàn). */
export function applyOverrides(style, ov = {}) {
  const { guide, hesitations, sfxNames, ...rest } = style;
  const st = { ...JSON.parse(JSON.stringify(rest)), guide, hesitations, sfxNames };
  const clamp = (v, a, b) => Math.min(b, Math.max(a, Number(v)));
  if (ov.zoomScale != null) st.zoom.scale = clamp(ov.zoomScale, 1, 1.6);
  if (ov.zoomMinGap != null) st.zoom.minGap = clamp(ov.zoomMinGap, 0.8, 60);
  if (ov.captionsMaxWords != null) st.captions.maxWords = Math.round(clamp(ov.captionsMaxWords, 1, 8));
  if (ov.musicGainDb != null) st.music.gainDb = clamp(ov.musicGainDb, -40, 0);
  if (ov.pause != null) st.pause = clamp(ov.pause, 0.15, 3);
  if (ov.sfxOff) { st.sfx.onZoom = null; st.sfx.max = 0; }
  return st;
}

function reviseText(words, keep) {
  // lời chép với mốc giây BẢN HIỆN TẠI cho chữ đang giữ; chữ đã bỏ đánh dấu ✗
  const lines = []; let line = [];
  const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };
  for (const w of words) {
    const to = toOutput(keep, (w.s + w.e) / 2);
    if (!line.length) line.push(to === null ? '(đã bỏ)' : `(${to.toFixed(1)}s)`);
    line.push(`[${w.i}]${w.w}${to === null ? '✗' : ''}`);
    if (/[.?!]$/.test(w.w) || line.length > 16) flush();
  }
  flush();
  return lines.join('\n');
}

export function buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors, previous }) {
  const outDur = outputDuration(timelineOf(edl));
  return `Mày là biên tập viên video ngắn tiếng Việt. Video đã dựng xong, dài ${outDur.toFixed(1)} giây (bản hiện tại). Người dùng muốn sửa:
"${instruction}"

Chỉ trả về MỘT khối JSON. Mốc giây người dùng nói là giây của BẢN HIỆN TẠI.

# Lời chép ([i] = số thứ tự chữ; đầu dòng là mốc giây bản hiện tại; chữ có ✗ là đã bỏ)
${reviseText(words, timelineOf(edl))}

# Đề xuất hiện tại
${JSON.stringify({ drop: proposal.drop, highlights: proposal.highlights, zooms: proposal.zooms, sfx: proposal.sfx, fixes: proposal.fixes, ...(proposal.hook ? { hook: proposal.hook } : {}), ...(proposal.quote ? { quote: proposal.quote } : {}), ...(proposal.hookText ? { hookText: proposal.hookText } : {}) })}

# Núm chỉnh kiểu hiện tại (${style.name})
${JSON.stringify({ zoomScale: style.zoom.scale, zoomMinGap: style.zoom.minGap, captionsMaxWords: style.captions.maxWords, musicGainDb: style.music.gainDb, pause: style.pause, ...overrides })}

# Tên riêng đúng
${namesText(names)}

# Định dạng trả về
{
  "proposal": { "drop": [...], "highlights": [...], "zooms": [...], "sfx": [...], "fixes": [...] },
  "cut_output": [{"start": <giây bản hiện tại>, "end": <giây>}],
  "style": { "zoomScale"?: 1–1.6, "zoomMinGap"?: giây, "captionsMaxWords"?: 1–8, "musicGainDb"?: -40–0, "pause"?: giây, "sfxOff"?: true },
  "notes": "<1 câu: đã đổi gì>"
}
Luật:
- "proposal" là bản ĐẦY ĐỦ sau khi sửa (cùng luật như lúc dựng: drop theo chỉ số chữ, "filler" chỉ cho từ đệm, sửa chữ dùng fixes). Không đổi thì chép lại đề xuất hiện tại.
- Yêu cầu theo thời gian ("bỏ 3 giây đầu", "bỏ đoạn 12s–15s") → "cut_output" theo giây bản hiện tại. Yêu cầu theo lời ("bỏ câu chào") → drop theo chữ.
- "zoom ít lại" → bớt zooms và/hoặc tăng zoomMinGap; "zoom mạnh hơn" → tăng zoomScale. Chỉ đưa vào "style" núm nào thật sự đổi.
- Không làm gì ngoài lời người dùng.
${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;
}

/** LLM đọc lời sửa → {proposal, cutsOut, overrides, notes}. Sai → sửa 1 vòng; vẫn sai → báo lỗi (không đoán bừa). */
export async function proposeRevision({ words, edl, proposal, style, overrides = {}, instruction, names, log = console.log, exclude = null }) {
  let text = ''; let prev = null; let cost = 0;
  const outDur = outputDuration(timelineOf(edl));
  for (let round = 1; round <= 2; round++) {
    const prompt = buildRevisePrompt({ words, edl, proposal, style, overrides, instruction, names, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });
    let errors = []; let out = null;
    try {
      const r = await callClaude(prompt, { log });
      text = r.text; cost += r.costUSD || 0;
      const j = parseProposal(text);
      // câu móc / trích dẫn / chữ móc: lời sửa không nhắc tới thì giữ như cũ
      const keepExtra = Object.fromEntries(['hook', 'quote', 'hookText'].filter((k) => proposal[k] != null).map((k) => [k, proposal[k]]));
      const checked = checkProposal({ ...keepExtra, ...(j.proposal || proposal) }, words, style, exclude);
      errors = checked.errors;
      const cuts = Array.isArray(j.cut_output) ? j.cut_output : [];
      for (const c of cuts) {
        if (!(Number.isFinite(c?.start) && Number.isFinite(c?.end) && c.start >= 0 && c.end > c.start && c.start < outDur)) {
          errors.push(`cut_output ${JSON.stringify(c)} không hợp lệ (0–${outDur.toFixed(1)} s, start < end)`);
        }
      }
      const ov = {};
      for (const k of ['zoomScale', 'zoomMinGap', 'captionsMaxWords', 'musicGainDb', 'pause']) {
        if (j.style?.[k] == null) continue;
        if (!Number.isFinite(Number(j.style[k]))) errors.push(`style.${k} không phải số`); else ov[k] = Number(j.style[k]);
      }
      if (j.style?.sfxOff) ov.sfxOff = true;
      out = {
        proposal: { ...checked.clean, notes: String(j.notes || '') },
        cutsOut: cuts.map((c) => ({ start: c.start, end: Math.min(c.end, outDur) })),
        overrides: { ...overrides, ...ov }, notes: String(j.notes || ''), costUSD: cost, rounds: round,
      };
    } catch (e) { errors = [`không đọc được JSON: ${e.message}`]; }
    if (!errors.length) return out;
    log(`LLM sửa vòng ${round}: ${errors.slice(0, 3).join('; ')}`);
    prev = { errors };
  }
  throw new Error('LLM không hiểu được lời sửa sau 2 vòng: ' + prev.errors.slice(0, 3).join('; '));
}