"""Insert the output of sbasm.py into the course RAM initializer and write the HDL to stdout or a file."""
import argparse
from pathlib import Path
import re
import sys
from tempfile import TemporaryDirectory


def assembled_words(text):
    text = re.sub(r"%[^%]*%|--[^\n]*", "", text.upper())
    header = r"\s*WIDTH\s*=\s*16\s*;\s*DEPTH\s*=\s*256\s*;\s*ADDRESS_RADIX\s*=\s*HEX\s*;\s*DATA_RADIX\s*=\s*HEX\s*;"
    data = re.fullmatch(header + r"\s*CONTENT\s+BEGIN\s+(.*?)\s*END\s*;\s*", text, re.S)
    if not data:
        raise ValueError("Assemble a 256-word program with sbasm.py first.")
    words = {}
    for entry in data[1].split(";"):
        if not entry.strip():
            continue
        row = re.fullmatch(r"\s*([0-9A-F]{1,2})\s*:\s*([0-9A-F]{1,4})\s*", entry)
        if not row:
            raise ValueError("Expected one 16-bit word per hexadecimal address.")
        address, value = (int(field, 16) for field in row.groups())
        if address in words:
            raise ValueError(f"Duplicate word address {address:02X}")
        words[address] = value
    if 0 not in words:
        raise ValueError("There is no instruction at address zero.")
    return words


def load_program(mif, hdl):
    words = assembled_words(mif.read_text(encoding="utf-8-sig"))
    lines = hdl.read_text(encoding="utf-8-sig").splitlines()
    def marker(name):
        matches = [i for i,line in enumerate(lines) if line.strip().endswith(name + " ASSEMBLED PROGRAM")]
        if len(matches) != 1:
            raise ValueError("Select the course HDL with both program markers.")
        return matches[0]
    start, end = marker("BEGIN"), marker("END")
    if end <= start:
        raise ValueError("The program markers are in the wrong order.")
    if hdl.suffix == ".vhd":
        body = [f'        {address} => x"{word:04X}",' for address,word in sorted(words.items())]
    elif hdl.suffix in (".v",".sv"):
        body = [f"        memory[{address}] = 16'h{word:04X};" for address,word in sorted(words.items())]
    else:
        raise ValueError("Choose .v, .sv or .vhd.")
    return "\n".join(lines[:start+1] + body + lines[end:]) + "\n"


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mif", type=Path)
    parser.add_argument("hdl", type=Path)
    parser.add_argument("--output", type=Path, help="Save UTF-8 HDL to a separate file.")
    args = parser.parse_args()
    try:
        text = load_program(args.mif, args.hdl)
        if args.output is None:
            sys.stdout.write(text)
        else:
            if args.output.suffix != args.hdl.suffix:
                raise ValueError("The output must use the same HDL file extension as the design.")
            if args.output.resolve() == args.hdl.resolve():
                raise ValueError("Choose a separate output file to keep your design.")
            with TemporaryDirectory(dir=args.output.parent) as folder:
                temporary = Path(folder) / args.output.name
                temporary.write_bytes(text.encode("utf-8"))
                temporary.replace(args.output)
    except (ValueError,OSError) as exc:
        parser.exit(1,str(exc)+"\n")
