using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;

namespace MaddoShared;

public sealed class VersionProvider : IVersionProvider
{
    public string GetVersionString()
    {
        // Prefer the entry assembly; fall back to executing assembly
        var asm = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();

        // 1) AssemblyInformationalVersion
        var infoAttr = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
        if (!string.IsNullOrWhiteSpace(infoAttr?.InformationalVersion))
        {
            return infoAttr.InformationalVersion!;
        }

        // 2) File product version
        try
        {
            var location = asm.Location;
            if (!string.IsNullOrWhiteSpace(location))
            {
                var fvi = FileVersionInfo.GetVersionInfo(location);
                if (!string.IsNullOrWhiteSpace(fvi.ProductVersion))
                    return fvi.ProductVersion!;
            }
        }
        catch
        {
            // ignore and fall back to assembly version
        }

        // 3) AssemblyName.Version formatted (avoid -1 and trailing .0 parts)
        var ver = asm.GetName().Version;
        if (ver is not null)
        {
            // Build a list of parts but ignore negative values
            var parts = new List<int> { ver.Major, ver.Minor };
            if (ver.Build >= 0) parts.Add(ver.Build);
            if (ver.Revision >= 0) parts.Add(ver.Revision);

            // Trim trailing zeros but keep at least major.minor
            for (int i = parts.Count - 1; i > 1; i--)
            {
                if (parts[i] == 0)
                    parts.RemoveAt(i);
                else
                    break;
            }

            return string.Join('.', parts);
        }

        return "0.0.0";
    }
}
