using System.Reflection;

namespace ClawdDotNet.UI;

public static class EmbeddedUiManager
{
    private static string? _extractedPath;

    public static string ExtractToTemp()
    {
        if (_extractedPath is not null) return _extractedPath;

        var tempDir = Path.Combine(Path.GetTempPath(), "ClawdDotNet_UI",
            Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "dev");

        Directory.CreateDirectory(tempDir);

        var asm = Assembly.GetExecutingAssembly();
        var prefix = "ClawdDotNet.EmbeddedUI.";

        foreach (var name in asm.GetManifestResourceNames()
                     .Where(n => n.StartsWith(prefix)))
        {
            // "ClawdDotNet.EmbeddedUI.chat.html" → "chat.html"
            var fileName = name[prefix.Length..];
            var dest = Path.Combine(tempDir, fileName);

            using var stream = asm.GetManifestResourceStream(name)!;
            using var file = File.Create(dest);
            stream.CopyTo(file);
        }

        _extractedPath = tempDir;
        return tempDir;
    }

    public static string GetExtractedPath()
        => _extractedPath ?? throw new InvalidOperationException(
            "EmbeddedUiManager.ExtractToTemp() must be called first.");
}
