using System;
using System.IO;
using System.Runtime.Loader;
using System.Windows.Baml2006;
using System.Xaml;
using System.Xml;

if (args.Length < 3)
{
    Console.WriteLine("Usage: baml2xaml <assemblyDir> <input.baml> <output.xaml>");
    return 1;
}

var assemblyDir = args[0];
var inputBaml = args[1];
var outputXaml = args[2];

AssemblyLoadContext.Default.Resolving += (context, name) =>
{
    var candidate = Path.Combine(assemblyDir, name.Name + ".dll");
    if (File.Exists(candidate))
    {
        return context.LoadFromAssemblyPath(candidate);
    }

    return null;
};

// Preload the main assembly if present to help resolve types referenced by BAML.
var mainAsm = Path.Combine(assemblyDir, "OLD_UKRAINE_GTA_Launcher.dll");
if (File.Exists(mainAsm))
{
    AssemblyLoadContext.Default.LoadFromAssemblyPath(mainAsm);
}

using var input = File.OpenRead(inputBaml);
var reader = new Baml2006Reader(input);

var settings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true
};

using var output = File.Create(outputXaml);
using var xmlWriter = XmlWriter.Create(output, settings);
using var xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());

XamlServices.Transform(reader, xamlWriter);

Console.WriteLine("OK");
return 0;
