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

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

foreach (var file in args)
{
    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 < args.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;
}

var cPaths = new List<string>();

Directory.CreateDirectory(".build");

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

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

    var path = Path.Combine(".build", Path.ChangeExtension(file, "c"));
    File.WriteAllText(path, generator.Emit());
    cPaths.Add(path);
}

var objectPaths = new List<string>();

foreach (var cPath in cPaths)
{
    var objectPath = Path.ChangeExtension(cPath, "o");
    using var compileProcess = Process.Start("clang", [
        "-ffreestanding", "-std=c23",
        "-g", "-c",
        "-o", objectPath,
        cPath,
    ]);

    compileProcess.WaitForExit();

    if (compileProcess.ExitCode != 0)
    {
        Console.Error.WriteLine($"clang failed with exit code {compileProcess.ExitCode}");
        return 1;
    }

    objectPaths.Add(objectPath);
}

Console.Out.WriteLine(string.Join(' ', objectPaths));

return 0;