using NubLang.Ast;
using NubLang.Diagnostics;
using NubLang.Generation;
using NubLang.Modules;
using NubLang.Syntax;

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

var tokenizer = new Tokenizer();
var parser = new Parser();
var generator = new LlvmGenerator();

foreach (var file in args)
{
    var tokens = tokenizer.Tokenize(file, File.ReadAllText(file));
    diagnostics.AddRange(tokenizer.Diagnostics);

    var syntaxTree = parser.Parse(tokens);
    diagnostics.AddRange(parser.Diagnostics);

    syntaxTrees.Add(syntaxTree);
}

ModuleRepository moduleRepository;

try
{
    moduleRepository = ModuleRepository.Create(syntaxTrees);
}
catch (CompileException e)
{
    Console.Error.WriteLine(e.Diagnostic.FormatANSI());
    return 1;
}

var compilationUnits = new List<List<TopLevelNode>>();

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

    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;
}

Directory.CreateDirectory(".build");

for (var i = 0; i < args.Length; i++)
{
    var file = args[i];
    var compilationUnit = compilationUnits[i];

    var directory = Path.GetDirectoryName(file);
    if (!string.IsNullOrWhiteSpace(directory))
    {
        Directory.CreateDirectory(Path.Combine(".build", directory));
    }

    var path = Path.Combine(".build", Path.ChangeExtension(file, "ll"));
    File.WriteAllText(path, generator.Emit(compilationUnit, moduleRepository));
}

return 0;