using System;
using System.IO;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Tornado3_2026Election.Domain;

namespace Tornado3_2026Election.Services;

public static class CutPreviewAssetCatalog
{
    private const string PreviewRootFolderName = "Tornado3_2026Election";
    private const string PreviewFolderName = "CutPreviews";

    public static string CreateCapturePath(BroadcastChannel channel, Guid itemId, string role)
    {
        var directory = GetPreviewDirectory();
        Directory.CreateDirectory(directory);

        var timestamp = DateTimeOffset.Now.ToString("yyyyMMdd_HHmmss_fff");
        var safeRole = SanitizeFileName(role);
        return Path.Combine(directory, $"{channel}_{safeRole}_{itemId:N}_{timestamp}.png");
    }

    public static ImageSource? CreateImageSource(string? path)
    {
        return !string.IsNullOrWhiteSpace(path) && File.Exists(path)
            ? new BitmapImage(new Uri(path, UriKind.Absolute))
            : null;
    }

    private static string GetPreviewDirectory()
    {
        var localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var root = string.IsNullOrWhiteSpace(localApplicationData)
            ? AppContext.BaseDirectory
            : localApplicationData;

        return Path.Combine(root, PreviewRootFolderName, PreviewFolderName);
    }

    private static string SanitizeFileName(string value)
    {
        var invalidCharacters = Path.GetInvalidFileNameChars();
        var sanitized = string.Join(
            "_",
            (value ?? string.Empty)
                .Split(invalidCharacters, StringSplitOptions.RemoveEmptyEntries));

        return string.IsNullOrWhiteSpace(sanitized)
            ? "preview"
            : sanitized;
    }
}
