using System.Text.Json; using ClipForge.Core.Entities; using ClipForge.Core.Interfaces; using ClipForge.Core.Interfaces.Services; using ClipForge.Infrastructure.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClipForge.Infrastructure.Services; public class VideoAssemblyService : IVideoAssemblyService { private readonly IVideoScriptRepository _scriptRepository; private readonly IRepository _voiceRepository; private readonly IVideoAssetRepository _videoAssetRepository; private readonly IFfmpegService _ffmpeg; private readonly IStockMediaService _stockMedia; private readonly ISubtitleService _subtitleService; private readonly StorageSettings _storage; private readonly ILogger _logger; public VideoAssemblyService( IVideoScriptRepository scriptRepository, IRepository voiceRepository, IVideoAssetRepository videoAssetRepository, IFfmpegService ffmpeg, IStockMediaService stockMedia, ISubtitleService subtitleService, IOptions storage, ILogger logger) { _scriptRepository = scriptRepository; _voiceRepository = voiceRepository; _videoAssetRepository = videoAssetRepository; _ffmpeg = ffmpeg; _stockMedia = stockMedia; _subtitleService = subtitleService; _storage = storage.Value; _logger = logger; } public async Task AssembleVideoAsync(Guid scriptId, CancellationToken ct = default) { var script = await _scriptRepository.GetByIdAsync(scriptId, ct) ?? throw new InvalidOperationException($"Script {scriptId} not found"); _logger.LogInformation("Starting video assembly for script {ScriptId}", scriptId); // Create video asset record var videoAsset = new VideoAsset { VideoScriptId = scriptId, Status = "processing" }; await _videoAssetRepository.AddAsync(videoAsset, ct); try { // 1. Get voice asset (should already exist) var voiceAssets = await _voiceRepository.GetAllAsync(ct); var voiceAsset = voiceAssets.FirstOrDefault(v => v is VoiceAsset va && va.VideoScriptId == scriptId) as VoiceAsset ?? throw new InvalidOperationException($"Voice asset not found for script {scriptId}. Generate voice first."); // 2. Download background clips from YouTube var scenes = ParseScenes(script.Scenes); var tempDir = Path.Combine(_storage.BasePath, _storage.TempFolder, videoAsset.Id.ToString()); Directory.CreateDirectory(tempDir); var backgroundClips = new List(); // Use the first 2 most specific scene descriptions as search queries var searchQueries = scenes.Take(4).ToList(); foreach (var query in searchQueries) { if (backgroundClips.Count >= 12) break; var neededPerQuery = Math.Max(3, (12 - backgroundClips.Count)); var clips = await _stockMedia.DownloadMultipleVideosAsync(query, neededPerQuery, tempDir, ct); backgroundClips.AddRange(clips); } // If still not enough, try a broader search with the topic if (backgroundClips.Count < 3) { var idea = await _scriptRepository.GetByIdAsync(scriptId, ct); var broadQuery = script.ScriptText[..Math.Min(60, script.ScriptText.Length)]; var extras = await _stockMedia.DownloadMultipleVideosAsync(broadQuery, 4, tempDir, ct); backgroundClips.AddRange(extras); } if (backgroundClips.Count == 0) throw new InvalidOperationException("Could not download any background clips for the video."); // 3. Assemble video var videoDir = Path.Combine(_storage.BasePath, _storage.VideoFolder); Directory.CreateDirectory(videoDir); var rawVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}_raw.mp4"); await _ffmpeg.AssembleVerticalVideoAsync(voiceAsset.FilePath, backgroundClips, rawVideoPath, ct); // 4. Generate subtitles var duration = await _ffmpeg.GetMediaDurationAsync(rawVideoPath, ct); videoAsset.DurationSeconds = duration; await _videoAssetRepository.UpdateAsync(videoAsset, ct); var captionAsset = await _subtitleService.GenerateSubtitlesAsync(videoAsset.Id, ct); // 5. Burn subtitles into video var finalVideoPath = Path.Combine(videoDir, $"{videoAsset.Id}.mp4"); await _ffmpeg.AddSubtitlesToVideoAsync(rawVideoPath, captionAsset.SrtFilePath, finalVideoPath, ct); // 6. Generate thumbnail var thumbDir = Path.Combine(_storage.BasePath, _storage.ThumbnailFolder); Directory.CreateDirectory(thumbDir); var thumbPath = Path.Combine(thumbDir, $"{videoAsset.Id}.jpg"); await _ffmpeg.GenerateThumbnailAsync(finalVideoPath, thumbPath, ct: ct); // 7. Update video asset var fileInfo = new FileInfo(finalVideoPath); videoAsset.FilePath = finalVideoPath; videoAsset.ThumbnailPath = thumbPath; videoAsset.FileSizeBytes = fileInfo.Length; videoAsset.DurationSeconds = await _ffmpeg.GetMediaDurationAsync(finalVideoPath, ct); videoAsset.Status = "completed"; await _videoAssetRepository.UpdateAsync(videoAsset, ct); // Cleanup raw video if (File.Exists(rawVideoPath)) File.Delete(rawVideoPath); _logger.LogInformation("Video assembly completed: {FilePath}", finalVideoPath); return videoAsset; } catch (Exception ex) { _logger.LogError(ex, "Video assembly failed for script {ScriptId}", scriptId); videoAsset.Status = "failed"; await _videoAssetRepository.UpdateAsync(videoAsset, ct); throw; } } private static List ParseScenes(string scenesJson) { try { using var doc = JsonDocument.Parse(scenesJson); var scenes = new List(); foreach (var element in doc.RootElement.EnumerateArray()) { if (element.TryGetProperty("description", out var desc)) scenes.Add(desc.GetString() ?? "nature"); } return scenes.Count > 0 ? scenes : ["nature", "city", "technology"]; } catch { return ["nature", "city", "technology"]; } } }