using Microsoft.Extensions.Hosting.Internal;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace YTExtractor
{
    public class YoutubeService
    {
        public static bool IsValidYouTubeUrl(string urlx)
        {
            return Regex.IsMatch(urlx, @"^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$");
        }

        public static async Task<YtDlpInfo> GetVideoInfo(string url, string workingDir)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "yt-dlp",
                Arguments = $"--dump-json {url}",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                WorkingDirectory = workingDir
            };

            using var process = Process.Start(startInfo);
            var output = await process.StandardOutput.ReadToEndAsync();
            await process.WaitForExitAsync();

            if (process.ExitCode != 0)
                throw new Exception("Failed to get video info");

            var jsonDoc = JsonDocument.Parse(output);
            var root = jsonDoc.RootElement;

            return new YtDlpInfo(
                root.GetProperty("title").GetString() ?? "",
                root.GetProperty("thumbnail").GetString() ?? ""
            );
        }

        public static async Task<string> GetSubtitles(string url, string language, string workingDir)
        {
            var pathExe = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var exePath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? Path.Combine(pathExe, "yt-dlp.exe")
                : "yt-dlp"; 
            
            //var wokingExe = Path.Combine(pathExe, "yt-dlp.exe");
            var startInfo = new ProcessStartInfo
            {
                FileName = exePath,
                Arguments = $"--write-sub --write-auto-sub --sub-lang {language} --skip-download {url}",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                WorkingDirectory = workingDir
            };

            using var process = Process.Start(startInfo);
            var output = await process.StandardOutput.ReadToEndAsync();
            var error = await process.StandardError.ReadToEndAsync();
            await process.WaitForExitAsync();

            var subtitleFile = Directory.GetFiles(workingDir, "*.vtt").FirstOrDefault();
            if (subtitleFile == null)
                throw new Exception("No subtitles found");

            return await File.ReadAllTextAsync(subtitleFile);
        }
    }
}
