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

var options = new Options();

for (var i = 0; i < args.Length; i++)
{
    var arg = args[i];
    switch (arg)
    {
        case "-o":
        {
            ++i;
            if (i >= args.Length)
            {
                return 1;
            }

            options.OutputPath = args[i];
            break;
        }
        default:
        {
            options.Files.Add(arg);
            break;
        }
    }
}

foreach (var file in options.Files)
{
    if (!File.Exists(file))
    {
        Console.Error.WriteLine($"File '{file}' does not exist");
        return 1;
    }
}

var diagnostics = new List<Diagnostic>();

var syntaxTrees = new List<SyntaxTree>();
foreach (var file in options.Files)
{
    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 moduleRepository = new ModuleRepository(syntaxTrees);

var definitions = new List<DefinitionNode>();

var referencedStructTypes = new HashSet<NubStructType>();

foreach (var syntaxTree in syntaxTrees)
{
    var typeChecker = new TypeChecker(syntaxTree, moduleRepository);
    typeChecker.Check();

    definitions.AddRange(typeChecker.Definitions);
    diagnostics.AddRange(typeChecker.Diagnostics);

    foreach (var structType in typeChecker.ReferencedStructTypes)
    {
        referencedStructTypes.Add(structType);
    }
}

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

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

Directory.CreateDirectory(".build");

var generator = new Generator(definitions, referencedStructTypes);
var c = generator.Emit();
var cFilePath = Path.Combine(".build", "out.c");

File.WriteAllText(cFilePath, c);

using var process = Process.Start("gcc", ["-ffreestanding", "-nostartfiles", "-c", "-o", Path.Combine(".build", "out.o"), cFilePath]);

process.WaitForExit();

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

return 0;