using NubLang.CLI;
using NubLang.Code;
using NubLang.Diagnostics;
using NubLang.Generation.QBE;
using NubLang.Modules;
using NubLang.Parsing;
using NubLang.Parsing.Syntax;
using NubLang.Tokenization;
using NubLang.TypeChecking;
using NubLang.TypeChecking.Node;

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(new SourceFile(arg));
            break;
        }
    }
}

foreach (var file in options.Files)
{
    if (!File.Exists(file.Path))
    {
        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);
    var tokens = tokenizer.Tokenize().ToList();
    diagnostics.AddRange(tokenizer.GetDiagnostics());

    var parser = new Parser();
    var syntaxTree = parser.Parse(tokens);

    diagnostics.AddRange(parser.GetDiagnostics());

    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 QBEGenerator(definitions, referencedStructTypes);
var ssa = generator.Emit();
var ssaFilePath = Path.Combine(".build", "out.ssa");
File.WriteAllText(ssaFilePath, ssa);

var asmFilePath = Path.Combine(".build", "out.asm");
var qbeSuccess = await QBE.Invoke(ssaFilePath, asmFilePath);
if (!qbeSuccess) return 1;

var objFilePath = Path.Combine(".build", "out.o");
var asmSuccess = await GCC.Assemble(asmFilePath, objFilePath);
if (!asmSuccess) return 1;

return 0;