using System;
using System.IO;
using System.Linq;
using Tornado3_2026Election.Domain;

namespace Tornado3_2026Election.Services;

internal static class KarismaSceneResolver
{
    public static KarismaResolvedScene ResolveScene(
        FormatTemplateDefinition template,
        string t3CutPath,
        bool useLoop,
        bool useEnd = false)
    {
        return ResolveScene(template, template.Cuts.FirstOrDefault(), t3CutPath, useLoop, useEnd);
    }

    public static KarismaResolvedScene ResolveScene(
        FormatTemplateDefinition template,
        FormatCutDefinition? cut,
        string t3CutPath,
        bool useLoop,
        bool useEnd = false)
    {
        var sceneId = string.IsNullOrWhiteSpace(cut?.SceneIdOverride)
            ? template.Id
            : cut.SceneIdOverride!;
        var baseScenePath = Path.Combine(t3CutPath, sceneId + ".tscn");
        var loopScenePath = Path.Combine(t3CutPath, sceneId + "_loop.tscn");
        var endScenePath = Path.Combine(t3CutPath, sceneId + "_END.tscn");

        string selectedPath;
        if (useEnd && File.Exists(endScenePath))
        {
            selectedPath = endScenePath;
        }
        else if (useLoop && File.Exists(loopScenePath))
        {
            selectedPath = loopScenePath;
        }
        else if (File.Exists(baseScenePath))
        {
            selectedPath = baseScenePath;
        }
        else if (File.Exists(loopScenePath))
        {
            selectedPath = loopScenePath;
        }
        else
        {
            throw new FileNotFoundException($"Karisma cut file was not found for '{sceneId}'.", baseScenePath);
        }

        return new KarismaResolvedScene(
            selectedPath,
            template.Id.Replace('\\', '_').Replace('/', '_'));
    }

    public static bool HasEndScene(FormatTemplateDefinition template, string t3CutPath)
    {
        return template.Cuts
            .Select(cut => string.IsNullOrWhiteSpace(cut.SceneIdOverride) ? template.Id : cut.SceneIdOverride!)
            .Distinct(StringComparer.Ordinal)
            .Any(sceneId => File.Exists(Path.Combine(t3CutPath, sceneId + "_END.tscn")));
    }
}

internal readonly record struct KarismaResolvedScene(string Path, string Alias);
