#!/usr/bin/env python3

import sys
import argparse
from utils import copy
from core import run, reset
import core
from assamble import assamble, link

def slurp(path):
    with open(path, 'r') as file:
        return file.read()

def run_file(args):
    files = args.files
    assert len(files) < 2, "Executing more than one file at a time is not supported yet." 
    assert len(files) > 0, "You must specify at least one file to execute"

    # read the source code from a file
    path = files[0]
    source_code = slurp(path)

    # assamble (compile) into object code
    obj = assamble(source_code)
    binary = link(obj)

    # initialise the virtual machine
    reset()
    copy(binary, core.ram)

    # !
    core.trace = args.trace
    run() 
    print()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Assamble, link and run an assambler")
    parser.add_argument('--trace', action='store_true', help='enable tracing during execution')
    parser.add_argument('files', nargs='+', help='source file to execute')
    args = parser.parse_args()
    # print(args)
    run_file(args)

