using SWIFTFramework;
using SWIFTFramework.Messages.Category1;
using SWIFTFramework.Validation;

namespace ParseAndModify;

/// <summary>
/// Parse an MT103, print XML, change fields, and re-emit SWIFT text.
/// License key is never shipped — set SWIFTFRAMEWORK_RUNTIME_LICENSE_KEY or User Secrets.
/// </summary>
class Program
{
    static int Main(string[] args)
    {
        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 sampleMessage = """
            {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}}
            """;

        Console.WriteLine("=== Parse and modify MT103 ===");
        Console.WriteLine();

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

        Console.WriteLine($"Parsed message type: {message.GetType().Name}");
        Console.WriteLine($"Validation errors: {errors.Count}");
        foreach (var error in errors)
            Console.WriteLine($"  - {error.Type}: {error.Description}");

        Console.WriteLine();
        Console.WriteLine("--- XML ---");
        Console.WriteLine(message.ToXml());

        var mt103 = (MT103)message;
        mt103.Tag59_BeneficiaryCustomer.Value = "/1122334455";
        mt103.ValueDateCurrencyInterbankSettledAmount_32A.Date = DateTime.Today;

        Console.WriteLine();
        Console.WriteLine("--- Updated SWIFT text ---");
        Console.WriteLine(parser.GetMessageAsText(mt103));
        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);
    }
}
