using SWIFTFramework;
using SWIFTFramework.Validation;

namespace XmlRoundTrip;

/// <summary>
/// Parse FIN, export structured XML, import it back, and write FIN again.
/// License key is never shipped — set SWIFTFRAMEWORK_RUNTIME_LICENSE_KEY or User Secrets.
/// </summary>
class Program
{
    static int Main()
    {
        if (!TryApplyLicense())
        {
            Console.Error.WriteLine("No runtime license key found.");
            Console.Error.WriteLine("Set SWIFTFRAMEWORK_RUNTIME_LICENSE_KEY, or add SWIFTFramework:RuntimeLicenseKey to .NET User Secrets.");
            return 1;
        }

        string fin = """
            {1:F01BANKUSPPAXXX6453938350}{2:O1030805090112BANKUKZHH80A53405362810901120805N}{4:
            :20:ABCDEREF
            :23B:CRED
            :32A:090113USD14551,
            :33B:USD14551,
            :50K:/0123456789
            :52A:BANKUSPP
            :57A:/9876543210
            BANKUKZH
            :59:/9988776655
            :71A:SHA
            -}{5:{CHK:30860BAE4D8E}{MAC:00000000}}{S:{SAC:}{COP:P}}
            """;

        var parser = new SwiftParser();
        var errors = new List<ValidationError>();
        SwiftMessage original = parser.GetMessage(fin, errors);

        string xml = original.ToXml();
        Console.WriteLine("--- Structured XML ---");
        Console.WriteLine(xml);

        SwiftMessage restored = parser.GetMessageFromXml(xml);
        Console.WriteLine();
        Console.WriteLine("--- FIN after XML round-trip ---");
        Console.WriteLine(parser.GetMessageAsText(restored));
        Console.WriteLine($"Type: {restored.GetType().Name}, parse errors: {errors.Count}");
        return 0;
    }

    static bool TryApplyLicense()
    {
        string? key = Environment.GetEnvironmentVariable("SWIFTFRAMEWORK_RUNTIME_LICENSE_KEY");
        if (!string.IsNullOrWhiteSpace(key))
            Licensing.RunTimeLicenseKey = key.Trim();

        return !string.IsNullOrWhiteSpace(Licensing.RunTimeLicenseKey);
    }
}
