using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace ConsoleApp1;

public static class Playgournd
{
    public static void GetAllFiles(string basePath = @"\\192.168.31.10\media\downloads\aria2\TV\")
    {
        var files = Directory.GetFiles(basePath, "*", SearchOption.AllDirectories);
        
        files = files.Select(path => path.Replace(basePath, "").ToUnixPath()).ToArray();
        
        
        var result = new StringBuilder();
        foreach (var file in files)
        {
            result.AppendLine(file);
        }
        File.WriteAllText("questions.txt", result.ToString(), Encoding.UTF8);
    }

    public static async Task ParseQuestions(string path = "questions.txt")
    {
        var parser = new EpisodeParser();
        var questions = File.ReadAllLines(path);
        foreach (var question in questions)
        {
            parser.Append(question);
        }
        
        parser.Start();
        int current = -1;
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        while (parser.Running)
        {
            if (current != parser.CompletedQuestions)
            {
                var prompt = $"{parser.CompletedQuestions}/{parser.TotalQuestions}";
                if (current != -1)
                {
                    prompt += $", 预计剩余 {stopwatch.Elapsed.Seconds * parser.RestQuestions}s";
                    stopwatch.Restart();
                }
                current = parser.CompletedQuestions;
                Console.WriteLine(prompt);
            }
            await Task.Delay(1000);
        }
        
        var grouper = new EpisodeGroup();
        
        while (parser.TryGetResult(out var result))
        {
            if (!result.success)
            {
                Console.WriteLine($"解析失败: {result.originalQuestion}");
            }
            grouper.episodes.Add(result.parseResult);
        }
        
        grouper.Run();

        File.WriteAllText($"results_{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.json", JsonConvert.SerializeObject(grouper.episodes, Formatting.Indented), Encoding.UTF8);
    }
    
    public static async Task ReparseFailedQuestions(string path)
    {
        var parser = new EpisodeParser();
        var resultsJson = File.ReadAllText(path);
        var results = JsonConvert.DeserializeObject<List<EpisodeParseResult>>(resultsJson);
        var dict = new Dictionary<string, EpisodeParseResult>();

        for (int i = 0; i < results.Count; i++)
        {
            var result = results[i];
            if (result.success == false)
            {
                dict[result.originalQuestion] = result;
                parser.Append(result.originalQuestion);
            }
        }
        parser.Start();
        int current = -1;
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        while (parser.Running)
        {
            if (current != parser.CompletedQuestions)
            {
                var prompt = $"{parser.CompletedQuestions}/{parser.TotalQuestions}";
                if (current != -1)
                {
                    prompt += $", 预计剩余 {stopwatch.Elapsed.Seconds * parser.RestQuestions}s";
                    stopwatch.Restart();
                }
                current = parser.CompletedQuestions;
                Console.WriteLine(prompt);
            }
            await Task.Delay(1000);
        }
        
        while (parser.TryGetResult(out var result))
        {
            dict[result.originalQuestion].success = result.success;
            dict[result.originalQuestion].parseResult = result.parseResult;
        }

        File.WriteAllText($"results_{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.json", JsonConvert.SerializeObject(results), Encoding.UTF8);
    }
    
    public static async Task<ShowsManager> CalcShows(string path)
    {
        var resultsJson = File.ReadAllText(path);
        var results = JsonConvert.DeserializeObject<List<EpisodeParseResult>>(resultsJson);
        var showsManager = new ShowsManager();
        foreach (var result in results)
        {
            showsManager.AppendEpisode(result.parseResult);
        }
        return showsManager;
    }

    public static async Task Repair(string path, string qPath)
    {
        var parser = new EpisodeParser();
        var questions = File.ReadAllLines(qPath);
        
        var resultsJson = File.ReadAllText(path);
        var results = JsonConvert.DeserializeObject<List<EpisodeParseResult>>(resultsJson);
        var dict = new Dictionary<string, EpisodeParseResult>();

        for (int i = 0; i < results.Count; i++)
        {
            var result = results[i];
            if (questions.Contains(result.originalQuestion))
            {
                dict[result.originalQuestion] = result;
                parser.Append(result.originalQuestion);
            }
        }
        
        parser.Start();
        int current = -1;
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        while (parser.Running)
        {
            if (current != parser.CompletedQuestions)
            {
                var prompt = $"{parser.CompletedQuestions}/{parser.TotalQuestions}";
                if (current != -1)
                {
                    prompt += $", 预计剩余 {stopwatch.Elapsed.Seconds * parser.RestQuestions}s";
                    stopwatch.Restart();
                }
                current = parser.CompletedQuestions;
                Console.WriteLine(prompt);
            }
            await Task.Delay(1000);
        }
        
        while (parser.TryGetResult(out var result))
        {
            dict[result.originalQuestion].success = result.success;
            dict[result.originalQuestion].parseResult = result.parseResult;
        }

        File.WriteAllText($"results_{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.json", JsonConvert.SerializeObject(results), Encoding.UTF8);
    }
}