CenaForge: primeira versão pública

Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 16:35:09 -03:00
co-authored by Claude Opus 5.5
commit 84f30bbc2d
484 changed files with 74826 additions and 0 deletions
+524
View File
@@ -0,0 +1,524 @@
// Cliente do Clipador no navegador: tipos do contrato de /api/clipper/* (repassado a /v1/* do serviço
// Python em 127.0.0.1:4520), rótulos, formatação e o gancho de ações com retorno. Não importa de
// lib/clipper.ts, que roda só no servidor.
import { useCallback, useState } from "react";
import { apiCall, type ApiResult } from "./api-client";
import type { Tone } from "./ui";
export type ClipperPlatform = "twitch" | "youtube" | "kick";
export type JudgeProvider = "codex" | "claude" | "off";
export type ClipperStatus = {
version: string;
tools: { streamlink: string | null; ffmpeg: string | null };
voice: { configured: boolean; online: boolean };
judge: { provider: JudgeProvider; model: string; available: boolean; path: string | null; minScore: number };
recording: number;
settings: { quality: string; segmentS: number; pollS: number; keepHours: number; language: string };
};
export type JudgeModel = { id: string; label: string; description?: string };
/** `faceTrack` é opcional: o serviço antigo (antes do rastreio de reação) não manda. */
export type JudgeOptions = { scanEnabled: boolean; scanIntervalS: number; vision: boolean; camDetect: boolean; faceTrack?: boolean };
export type JudgeConfig = {
provider: JudgeProvider;
/** Modelo do EDITOR (2º juiz). null com o juiz desligado. */
model: string | null;
/** Modelo do ANALISTA (1º juiz, vê os frames); vem resolvido (igual ao editor quando não há um próprio). */
analystModel?: string | null;
available: boolean | null;
path: string | null;
minScore: number;
options?: JudgeOptions;
lastScanError?: string | null;
models: { codex: JudgeModel[]; claude: JudgeModel[]; defaults: { codex: string; claude: string } };
};
export type ClipperChannel = {
id: string;
platform: ClipperPlatform;
channel: string;
url: string;
displayName: string;
monitor: boolean;
authorized: boolean;
lastCheckAt: string | null;
lastStatus: "ao vivo" | "offline" | "";
createdAt: string;
};
export type SessionStatus = "starting" | "recording" | "processing" | "done" | "stopped" | "error" | "interrupted";
export type ClipStatus = "candidate" | "pending" | "rendering" | "ready" | "approved" | "rejected" | "discarded" | "published" | "error";
export type ClipperSession = {
id: number;
channelId: string | null;
platform: ClipperPlatform;
kind: "live" | "vod";
url: string;
title: string;
status: SessionStatus;
/** "connected" | "connecting" | "unsupported" | "off" | "error: …" */
chatStatus: string;
chatMessages: number;
durationS: number;
startedAt: string;
endedAt: string | null;
error: string | null;
segments: { total: number; analyzed: number; transcriptErrors: number };
clips: Partial<Record<ClipStatus, number>>;
// Fase 2 (opcionais: o serviço antigo não manda).
game?: string;
gameSource?: GameSource;
/** O que a IA viu na tela; pode divergir da categoria da plataforma. */
screenGame?: string;
gameHistory?: { game: string; source: GameSource; atS: number; at: string }[];
gameProfileReady?: boolean;
/** Até onde (s) a varredura da IA já assistiu. */
scannedUntilS?: number;
memory?: MemoryEntry[];
camDetect?: CamDetect | null;
roomId?: string | null;
hasOwnSettings?: boolean;
/** O que a captura gravou de fato (1º bloco de cada execução). null = sessão antiga ou ainda sem bloco; ausente = serviço antigo. */
capture?: CaptureInfo | null;
};
export type GameSource = "platform" | "screen" | "user" | "";
export type MemoryEntry = { fromS: number; toS: number; summary: string };
export type CamDetect = {
hasWebcam: boolean; cam: Rect | null; gameOnScreen?: boolean; frame?: string; at?: string;
/** Quem achou: yunet = local (rosto no quadro, sem IA) · ai = IA olhando quadros · manual = você marcou. */
source?: "yunet" | "ai" | "manual";
confidence?: number; fullFrame?: boolean;
};
/** Reação no rosto do streamer (rastreio local, reaction.py): pico, início e intensidade (z relativo ao normal dele). */
export type FaceReaction = {
peakS: number; onsetS: number; endS: number; intensity: number; strong: boolean;
label: "risada" | "grito" | "susto" | "choque" | "confuso" | "raiva" | "neutro";
};
export type Situation = "lag_ou_bug" | "jogada" | "falha_engracada" | "morte" | "susto" | "treta" | "conversa_engracada"
| "historia" | "informacao_do_jogo" | "reacao" | "outro";
/** O que o ANALISTA (1º juiz) viu: tela + fala + chat. */
export type ClipAnalysis = {
situation: string;
what_happened: string;
screen: string;
speech: string;
chat_meaning: string;
/** 0–1 */
confidence: number;
action_start_s: number;
reaction_end_s: number;
hook: string;
};
export type ClipJudge = null
| { model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string }
| { error: string };
export type ClipTags = { risada?: number; susto?: number; hype?: number; clip?: number };
export type Clip = {
id: number;
sessionId: number;
peakS: number;
startS: number;
endS: number;
durationS: number;
score: number;
source: "chat" | "audio" | "manual" | "ai" | "face";
reasons: {
peakRatio?: number; messages?: number; tags?: ClipTags; topMessages?: string[];
/** Emotes do chat no pico: nome → quantidade. */
emotes?: Record<string, number>;
// Cortes da varredura da IA (source "ai").
proposalTitle?: string; proposalScore?: number; proposalReason?: string; scanFromS?: number; scanToS?: number;
/** Reação no rosto do streamer dentro do trecho (opcional: só com câmera e rastreio ligado). */
face?: FaceReaction;
/** Corte de fonte "face": o apoio do áudio (sinal suavizado) e do chat (mensagens de reação) que deixou o rosto virar corte. */
support?: { audioZ: number; chatReactions: number };
};
judge: ClipJudge;
title: string;
caption: string;
transcript: string;
status: ClipStatus;
file: string | null;
thumb: string | null;
error: string | null;
createdAt: string;
updatedAt: string;
channelId: string | null;
platform: ClipperPlatform;
sessionUrl: string;
/** Editor de cortes: há projeto de edição (o render usa ele); capa gerada no export. Opcional: serviço antigo não manda. */
edit?: { updatedAt: string; exportedAt: string | null; cover: string | null; origin?: "ai" | "user" | null } | null;
/** Formato do vídeo renderizado. Opcional: o serviço antigo não manda (ausente = vertical). */
aspect?: Aspect;
};
/* ---------- Configuração do corte ---------- */
/** Retângulo normalizado (0–1) sobre o quadro original 16:9; x, y = canto superior esquerdo. */
export type Rect = { x: number; y: number; w: number; h: number };
export type LayoutMode = "auto" | "blur" | "cam_top" | "game_only" | "cam_only";
/** Formato do corte: vertical = 1080×1920 (Shorts/Reels/TikTok); horizontal = 1920×1080 (YouTube, jogo em tela cheia). */
export type Aspect = "vertical" | "horizontal";
export type CutSettings = {
layout: { mode: LayoutMode; cam: Rect | null; game: Rect | null; camHeight: number };
caption: {
enabled: boolean; font: string; size: number; color: string; highlight: string; outline: string;
outlineWidth: number; y: number | null; uppercase: boolean; maxWords: number;
};
credit: { enabled: boolean; position: "top" | "bottom"; size: number };
duration: { minS: number; maxS: number; backtrackS: number };
/** O serviço antigo não manda este grupo: use `withFormat` para preencher com vertical. */
format: { aspect: Aspect };
/** Estilo do gancho que o projeto da IA põe no começo. Opcional: o serviço antigo não manda (use `hookOf`). */
hook?: HookSettings;
/** Qualidade de gravação da live (vale na próxima gravação ou retomada). Opcional: o serviço antigo não manda. */
capture?: { quality: CaptureQuality };
};
/** Camada parcial (canal ou sessão): só o que ela fixa. */
export type CutLayer = { [G in keyof CutSettings]?: Partial<CutSettings[G]> };
export type SettingsPayload = {
own: CutLayer;
effective: CutSettings;
defaults: CutSettings;
modes: LayoutMode[];
fonts: string[];
/** Só nas configurações da sessão: a camada do canal (null se a sessão não tem canal). */
channel?: CutLayer | null;
// Opcionais (o serviço antigo não manda): formatos, fontes empacotadas e opções do gancho.
aspects?: Aspect[];
/** {família: "assets/fonts/….ttf"} das fontes empacotadas, relativo à raiz do repositório. */
fontFiles?: Record<string, string>;
hookStyles?: HookStyle[];
hookAnims?: HookAnim[];
/** Tamanho do vídeo e quadro lógico dos textos (ASS) de cada formato. */
frames?: Record<Aspect, FrameSize>;
/** Opções de qualidade de gravação, com o disco por hora medido (serviço antigo não manda). */
captureQualities?: CaptureOption[];
};
export type FrameResult = { t: number; file: string; version: string };
export type PreviewResult = { t: number; file: string; mode: LayoutMode; version: string; aspect?: Aspect };
/** Formato de um corte ou configuração; ausente (serviço antigo) = vertical. */
export function aspectOf(value: { aspect?: Aspect | null } | null | undefined): Aspect {
return value?.aspect === "horizontal" ? "horizontal" : "vertical";
}
/** Completa uma configuração vinda do serviço antigo (sem o grupo `format`) com o formato vertical. */
export function withFormat(settings: CutSettings): CutSettings {
return { ...settings, format: { aspect: aspectOf(settings.format) } };
}
/** Mescla campo a campo: base ← camadas (igual ao serviço). */
export function mergeSettings(base: CutSettings, ...layers: (CutLayer | null | undefined)[]): CutSettings {
const out = structuredClone(base);
for (const layer of layers) {
if (!layer) continue;
for (const group of new Set([...Object.keys(out), "format"]) as Set<keyof CutSettings>) {
const values = layer[group];
// Grupo que a base não tem (ex.: `format` com o serviço antigo): cria em vez de quebrar.
if (values) (out as Record<string, unknown>)[group] = { ...(out[group] ?? {}), ...values };
}
}
return out;
}
/**
* Camada mínima para salvar: campos que diferem da base de baixo, mais os que a camada já fixava
* (para não "soltar" um valor que o usuário fixou de propósito, mesmo igual ao herdado).
*/
export function layerFrom(draft: CutSettings, base: CutSettings, own: CutLayer | null | undefined): CutLayer {
const out: Record<string, Record<string, unknown>> = {};
for (const group of Object.keys(draft) as (keyof CutSettings)[]) {
const values = (draft[group] ?? {}) as Record<string, unknown>;
const under = (base[group] ?? {}) as Record<string, unknown>;
const pinned = (own?.[group] ?? {}) as Record<string, unknown>;
for (const key of Object.keys(values)) {
if (key in pinned || JSON.stringify(values[key]) !== JSON.stringify(under[key])) (out[group] ??= {})[key] = values[key];
}
}
return out as CutLayer;
}
/* ---------- Jogos e emotes ---------- */
export type GameProfile = {
name: string; summary: string; genre: string;
mechanics: string[]; clip_worthy: string[]; avoid: string[]; jargon: string[]; news: string[]; sources: string[];
/** Hashtags do jogo (a 1ª é a principal): entram em toda legenda de corte deste jogo, depois da do canal. */
hashtags?: string[];
};
export type Game = {
id: string; name: string; status: "pending" | "ready" | "error"; error: string | null;
model: string | null; researchedAt: string | null; profile: GameProfile | null;
/** Última edição à mão ou por pedido seu à IA (serviço antigo não manda). */
editedAt?: string | null;
/** Pedidos que você fez à IA; voltam em toda pesquisa nova. */
notes?: { text: string; at: string; section?: string }[];
};
export type Emote = { name: string; source: string; uses: number; weight: number; lastSeen: string | null };
/** Id do jogo no serviço (mesma regra de intel.game_id). */
export function gameIdOf(name: string): string {
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "desconhecido";
}
/** Chave do canal para os emotes: "<plataforma>-<login>" (ex.: twitch-skipnho). */
export function channelKeyOf(session: Pick<ClipperSession, "channelId" | "platform" | "url">): string {
if (session.channelId) return session.channelId;
const login = channelFromUrl(session.url).replace(/^@/, "").toLowerCase();
return login ? `${session.platform}-${login}` : "";
}
export type Timeline = { durationS: number; messagesPerS: number[]; ratio: number[]; loudnessDb: (number | null)[] };
/* ---------- Chamadas ---------- */
/** Chama /api/clipper/<path>. O erro do serviço ({error}) vira a mensagem. */
export function clipperCall<T>(path: string, method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" = "GET", body?: unknown): Promise<ApiResult<T>> {
return apiCall<T>(`/api/clipper/${path}`, method, body);
}
/** O painel responde "Clipador fora do ar…" (ou "não instalado") quando não alcança o serviço. */
export function isOfflineError(message: string): boolean {
return /fora do ar|não instalado/i.test(message);
}
export type ActionMessage = { ok: boolean; text: string } | null;
/**
* Ações com retorno: guarda qual está rodando (para o spinner certo), mostra sucesso/erro e,
* se deu certo, chama `onDone` (normalmente recarregar os dados).
*/
export function useClipperAction(onDone?: () => void) {
const [pending, setPending] = useState<string | null>(null);
const [message, setMessage] = useState<ActionMessage>(null);
const run = useCallback(async <T,>(key: string, call: () => Promise<ApiResult<T>>, success: string | ((data: T) => string)) => {
setPending(key);
setMessage(null);
const result = await call();
setPending(null);
if (!result.ok) {
setMessage({ ok: false, text: result.error });
return null;
}
setMessage({ ok: true, text: typeof success === "function" ? success(result.data) : success });
onDone?.();
return result.data;
}, [onDone]);
return { pending, message, setMessage, run };
}
/* ---------- Rótulos ---------- */
export const PLATFORM_LABEL: Record<ClipperPlatform, string> = { twitch: "Twitch", youtube: "YouTube", kick: "Kick" };
export const SESSION_STATUS: Record<SessionStatus, { label: string; tone: Tone; pulse?: boolean }> = {
starting: { label: "iniciando", tone: "info", pulse: true },
recording: { label: "gravando", tone: "danger", pulse: true },
processing: { label: "processando", tone: "info", pulse: true },
done: { label: "concluída", tone: "success" },
stopped: { label: "parada", tone: "neutral" },
error: { label: "erro", tone: "danger" },
interrupted: { label: "interrompida", tone: "warning" },
};
export const CLIP_STATUS: Record<ClipStatus, { label: string; tone: Tone; pulse?: boolean }> = {
candidate: { label: "esperando a IA", tone: "violet", pulse: true },
pending: { label: "na fila de render", tone: "info" },
rendering: { label: "renderizando", tone: "info", pulse: true },
ready: { label: "pronto para aprovar", tone: "accent" },
approved: { label: "aprovado", tone: "success" },
rejected: { label: "rejeitado", tone: "neutral" },
discarded: { label: "descartado pela IA", tone: "warning" },
published: { label: "publicado", tone: "success" },
error: { label: "erro", tone: "danger" },
};
export const CLIP_STATUS_ORDER: ClipStatus[] = ["candidate", "pending", "rendering", "ready", "approved", "published", "rejected", "discarded", "error"];
export const SOURCE_LABEL: Record<Clip["source"], string> = {
chat: "pico do chat", audio: "pico do áudio", manual: "corte manual", ai: "IA viu na tela", face: "reação no rosto",
};
export const FACE_LABEL: Record<FaceReaction["label"], string> = {
risada: "risada", grito: "grito", susto: "susto", choque: "choque", confuso: "confuso", raiva: "raiva", neutro: "neutro",
};
export const SITUATION_LABEL: Record<Situation, string> = {
lag_ou_bug: "lag ou bug", jogada: "jogada", falha_engracada: "falha engraçada", morte: "morte", susto: "susto", treta: "treta",
conversa_engracada: "conversa engraçada", historia: "história", informacao_do_jogo: "informação do jogo", reacao: "reação", outro: "outro",
};
export const GAME_SOURCE_LABEL: Record<GameSource, string> = {
platform: "categoria da plataforma", screen: "a IA viu na tela", user: "confirmado por você", "": "",
};
export const MODE_LABEL: Record<LayoutMode, { label: string; hint: string }> = {
auto: { label: "Automático", hint: "câmera em cima se houver" },
cam_top: { label: "Câmera em cima", hint: "webcam + jogo" },
blur: { label: "Desfoque", hint: "vídeo inteiro" },
game_only: { label: "Só o jogo", hint: "recorta o jogo" },
cam_only: { label: "Câmera inteira", hint: "só o streamer" },
};
export const TAG_LABEL: Record<keyof ClipTags, string> = { risada: "risada", susto: "susto", hype: "hype", clip: "“clip” no chat" };
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", off: "Desligado" };
/** Sessões que ainda mudam sozinhas (vale consultar de novo). */
export const ACTIVE_SESSION: SessionStatus[] = ["starting", "recording", "processing"];
/** Cortes que ainda mudam sozinhos (IA ou render). */
export const ACTIVE_CLIP: ClipStatus[] = ["candidate", "pending", "rendering"];
export function chatStatusInfo(status: string): { label: string; tone: Tone } {
if (status === "connected") return { label: "chat conectado", tone: "success" };
if (status === "connecting") return { label: "conectando ao chat", tone: "info" };
if (status === "unsupported") return { label: "sem chat (plataforma)", tone: "neutral" };
if (status === "off" || status === "") return { label: "chat desligado", tone: "neutral" };
return { label: "erro no chat", tone: "danger" };
}
/* ---------- Formatação ---------- */
/** Relógio "m:ss" ou "h:mm:ss". */
export function formatClock(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = String(total % 60).padStart(2, "0");
return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
}
/** Duração curta: "42 s", "4 min 30 s", "1 h 05 min". */
export function formatDuration(seconds: number): string {
const total = Math.max(0, Math.round(seconds));
if (total < 60) return `${total} s`;
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
if (h > 0) return `${h} h ${String(m).padStart(2, "0")} min`;
const s = total % 60;
return s ? `${m} min ${s} s` : `${m} min`;
}
export function formatScore(score: number): string {
return score.toLocaleString("pt-BR", { maximumFractionDigits: 1 });
}
/** Nome do canal a partir do link da live/VOD (twitch.tv/<canal>, kick.com/<canal>, youtube.com/@canal). */
export function channelFromUrl(url: string): string {
try {
const u = new URL(url);
const first = u.pathname.split("/").filter(Boolean)[0] ?? "";
if (u.hostname.includes("youtu")) return first.startsWith("@") ? first : u.hostname.replace(/^www\./, "");
return first === "videos" ? u.hostname.replace(/^www\./, "") : first || u.hostname;
} catch {
return url;
}
}
/** Rótulo de quem é a live: o nome do canal cadastrado ou o que dá para tirar do link. */
export function sourceName(channelId: string | null, url: string, channels: ClipperChannel[]): string {
const channel = channelId ? channels.find((c) => c.id === channelId) : undefined;
return channel?.displayName || channel?.channel || channelFromUrl(url);
}
/* ---------- Gancho, fontes e formatos (editor de cortes e "Configuração do corte") ---------- */
/** `plain` = texto solto (com caixa opcional); `banner` = tarja na largura toda, texto em maiúsculas em até 2 linhas. */
export type HookStyle = "plain" | "banner";
/** `slide`: a tarja atravessa a tela e o texto entra deslizando, borrado, e assenta nítido. */
export type HookAnim = "pop" | "fade" | "none" | "slide";
export type HookSettings = { style: HookStyle; bg: string; color: string; font: string; anim: HookAnim; seconds: number };
/** Tamanho do vídeo de saída e quadro lógico do ASS (no horizontal os textos são contados em 2560×1440). */
export type FrameSize = { width: number; height: number; canvasWidth: number; canvasHeight: number };
/** Espelho de `layout.DEFAULTS["hook"]` do serviço, só para quando ele não manda o grupo (serviço antigo). */
export const HOOK_FALLBACK: HookSettings = { style: "banner", bg: "#00FF00", color: "#FFFFFF", font: "Luckiest Guy", anim: "slide", seconds: 3 };
/** Grupo `hook` efetivo (o serviço antigo não manda: usa o espelho do padrão). */
export function hookOf(settings: Pick<CutSettings, "hook"> | null | undefined): HookSettings {
return { ...HOOK_FALLBACK, ...(settings?.hook ?? {}) };
}
export const HOOK_STYLE_LABEL: Record<HookStyle, { label: string; hint: string }> = {
banner: { label: "Tarja", hint: "faixa colorida na largura toda" },
plain: { label: "Simples", hint: "texto solto, com caixa opcional" },
};
export const HOOK_ANIM_LABEL: Record<HookAnim, string> = {
slide: "Deslizar com desfoque", pop: "Entrada pop", fade: "Aparecer suave", none: "Sem animação",
};
/** Fontes do Windows que o serviço sempre aceita (as empacotadas vêm de `fontFiles`). */
export const SYSTEM_FONTS = ["Arial Black", "Arial", "Impact", "Verdana", "Segoe UI Black", "Trebuchet MS"];
/* ---------- Qualidade de gravação (grupo `capture`) ---------- */
/** `best` = a maior resolução que a live oferece; as outras são teto (a maior variante que não passa dele). */
export type CaptureQuality = "best" | "1440p" | "1080p" | "720p" | "480p";
/** Uma opção do seletor, como o serviço manda em `captureQualities`. */
export type CaptureOption = {
id: CaptureQuality; label: string; maxHeight: number | null; gbPerHour: number; gbPerHourMax: number; hint: string;
};
/** Resolução, fps, codec e taxa lidos do 1º bloco da gravação (ffprobe). `mixed` = blocos em mais de uma resolução. */
export type CaptureInfo = {
quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string;
kbps: number | null; gbPerHour: number | null; fromIdx: number; at: string; mixed: boolean;
runs?: { fromIdx: number; quality: CaptureQuality; width: number; height: number; fps: number | null; codec: string }[];
};
/** "2560×1440 · 60 fps". */
export function captureLabel(info: Pick<CaptureInfo, "width" | "height" | "fps">): string {
return `${info.width}×${info.height}${info.fps ? ` · ${info.fps} fps` : ""}`;
}
/** "3,2 GB/h" (ou "3,2–4,5 GB/h" quando a opção tem faixa). */
export function gbPerHourLabel(min: number, max?: number | null): string {
const f = (v: number) => v.toLocaleString("pt-BR", { maximumFractionDigits: v < 1 ? 2 : 1 });
return max && max - min >= 0.2 ? `${f(min)}–${f(max)} GB/h` : `${f(min)} GB/h`;
}
/* ---------- Apagar cortes (DELETE clips/<id> · POST clips/delete) ---------- */
/** Por que um corte não foi apagado. `busy_*` = o motor está mexendo nele; `published` = falta confirmar. */
export type ClipDeleteCode = "not_found" | "busy_candidate" | "busy_rendering" | "published" | "changed";
/** Arquivo que ficou no disco (fora das pastas do Clipador, ou em uso). */
export type ClipLeftFile = { file: string; reason: string };
export type ClipDeleted = { id: number; sessionId: number; status: ClipStatus; removedFiles: number; left: ClipLeftFile[] };
export type ClipDeleteFailure = { id: number; code: ClipDeleteCode; reason: string };
/** Resposta do lote: `remaining` = quantos passaram do limite de uma chamada (500). */
export type ClipDeleteResult = { requested: number; remaining: number; deleted: ClipDeleted[]; failed: ClipDeleteFailure[] };
/** Máximo de cortes numa chamada de lote (`clip_delete.MAX_BATCH` do serviço). */
export const CLIP_DELETE_MAX = 500;
/** Estados que o serviço recusa apagar (a IA ou o render está trabalhando no corte). */
export const UNDELETABLE_CLIP: ClipStatus[] = ["candidate", "rendering"];
/** "12 apagados, 1 não pôde: está renderizando" (motivos iguais agrupados). */
export function deleteSummary(result: Pick<ClipDeleteResult, "deleted" | "failed">): string {
const n = result.deleted.length;
const parts = [n === 1 ? "1 corte apagado" : `${n} cortes apagados`];
if (result.failed.length) {
const reasons = new Map<string, number>();
for (const f of result.failed) reasons.set(f.reason, (reasons.get(f.reason) ?? 0) + 1);
const why = [...reasons].map(([reason, k]) => (reasons.size > 1 ? `${k} ${reason}` : reason)).join("; ");
parts.push(`${result.failed.length} não pôde${result.failed.length === 1 ? "" : "ram"}: ${why}`);
}
const left = result.deleted.reduce((sum, d) => sum + (d.left?.length ?? 0), 0); // resposta sem `left` = nada ficou
if (left) parts.push(`${left} arquivo${left === 1 ? " ficou" : "s ficaram"} no disco`);
return parts.join(", ");
}