using System.Diagnostics;
using System.Text;
using LLVMSharp.Interop;
using NubLang.Ast;
using NubLang.Diagnostics;
using NubLang.Generation;
using NubLang.Syntax;

var diagnostics = new List<Diagnostic>();
var syntaxTrees = new List<SyntaxTree>();

var nubFiles = args.Where(x => Path.GetExtension(x) == ".nub").ToArray();
var objectFileArgs = args.Where(x => Path.GetExtension(x) is ".o" or ".a").ToArray();

foreach (var file in nubFiles)
{
    var tokenizer = new Tokenizer(file, File.ReadAllText(file));
    tokenizer.Tokenize();
    diagnostics.AddRange(tokenizer.Diagnostics);

    var parser = new Parser();
    var syntaxTree = parser.Parse(tokenizer.Tokens);
    diagnostics.AddRange(parser.Diagnostics);

    syntaxTrees.Add(syntaxTree);
}

var modules = Module.Collect(syntaxTrees);
var compilationUnits = new List<CompilationUnit>();

for (var i = 0; i < nubFiles.Length; i++)
{
    var typeChecker = new TypeChecker(syntaxTrees[i], modules);
    var compilationUnit = typeChecker.Check();

    compilationUnits.Add(compilationUnit);
    diagnostics.AddRange(typeChecker.Diagnostics);
}

foreach (var diagnostic in diagnostics)
{
    Console.Error.WriteLine(diagnostic.FormatANSI());
}

if (diagnostics.Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error))
{
    return 1;
}

for (var i = 0; i < nubFiles.Length; i++)
{
    var generator = new Generator(compilationUnits[i], nubFiles[i]);
    var module = generator.Generate();

    var outPath = Path.ChangeExtension(Path.Combine(".build", nubFiles[i]), "ll");
    var outDir = Path.GetDirectoryName(outPath);
    if (outDir != null)
    {
        Directory.CreateDirectory(outDir);
    }

    File.WriteAllText(outPath, module.PrintToString());
}

return 0;