namespace RolemasterDb.CriticalParsing;

public static class PowerPointModifierNotation
{
    public static string? NormalizeExpression(string? expression, char? forcedSign = null)
    {
        if (string.IsNullOrWhiteSpace(expression))
        {
            return null;
        }

        var normalized = CriticalCellParserSupport.CollapseWhitespace(expression)
            .Replace(" ", string.Empty, StringComparison.Ordinal);

        if (normalized.StartsWith('(') && normalized.EndsWith(')') && normalized.Length > 2)
        {
            normalized = normalized[1..^1];
        }

        char? sign = forcedSign;
        if (normalized.Length > 0 && (normalized[0] == '+' || normalized[0] == '-'))
        {
            sign ??= normalized[0];
            normalized = normalized[1..];
        }

        if (string.IsNullOrWhiteSpace(normalized))
        {
            return null;
        }

        return sign.HasValue
            ? $"{sign}{normalized}"
            : normalized;
    }

    public static string? FormatSignedExpression(string? expression)
    {
        var normalized = NormalizeExpression(expression);
        if (string.IsNullOrWhiteSpace(normalized))
        {
            return null;
        }

        return normalized[0] is '+' or '-'
            ? normalized
            : $"+{normalized}";
    }
}
