#!/usr/bin/env python3
"""tms-cc -- a small C driver for the TMS34010 toolchain.

This is the Phase 1 usability driver: it hides the bit-address IR barrier,
llc, the OS/2/GSPA entry assembly and tms-link behind a conventional
compile/link interface.

  tms-cc hello.c -o hello.coff        # link with the conformance shim + entry
  tms-cc -c hello.c -o hello.o        # relocatable TI-COFF object
  tms-cc -S hello.c -o hello.s        # GSPA assembly

The default link uses the freestanding conformance shim (printf/sprintf/
malloc/free/string) and its entry, so `tms-run hello.coff` can display the
output.  `-nostdlib` omits the shim; `-l NAME`/`-L DIR` add SDK archives.
The compiler pipeline itself remains `scripts/tms-clang` + `llc`; GSPLNK is
still the byte/symbol oracle for the gates.
"""
from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
TMS_CLANG = ROOT / "scripts/tms-clang"
LLC = Path(os.environ.get("TMS_LLC", ROOT / "build/llvm-clean-build/bin/llc"))
RUN_SH = ROOT / "scripts/m4/run.sh"
CONF = ROOT / "scripts/tests/m5/conformance"
ENTRY = CONF / "entry.asm"
SDK = ROOT / "sdk"
SHIM = SDK / "shim.c"
HEAP = SDK / "heap.c"
INCLUDE = SDK / "include"
TMS_LINK = ROOT / "tools/tms-link/tms-link"


def fail(msg: str, code: int = 1):
    print(f"tms-cc: error: {msg}", file=sys.stderr)
    raise SystemExit(code)


def tool(path: Path) -> Path:
    if not path.is_file():
        fail(f"missing tool: {path}")
    return path


def opt_level(args) -> str:
    if args.O0:
        return "-O0"
    if args.opt in ("0",):
        return "-O0"
    return "-O2"


def compile_ir(src: Path, dst: Path, opt: str, args):
    cmd = [str(TMS_CLANG), opt]
    if args.g:
        cmd.append("-g")
    for inc in [str(INCLUDE)] + list(args.includes):
        cmd += ["-I", inc]
    cmd += ["-o", str(dst), str(src)]
    if args.verbose:
        print("+", " ".join(cmd), file=sys.stderr)
    subprocess.run(cmd, check=True)


def llc_obj(ir: Path, dst: Path, args):
    cmd = [str(LLC), "-march=tms34010", "-O0", "-filetype=obj",
           str(ir), "-o", str(dst)]
    if args.verbose:
        print("+", " ".join(cmd), file=sys.stderr)
    subprocess.run(cmd, check=True)


def llc_asm(ir: Path, dst: Path, args):
    cmd = [str(LLC), "-march=tms34010", "-O0", "-filetype=asm",
           str(ir), "-o", str(dst)]
    if args.verbose:
        print("+", " ".join(cmd), file=sys.stderr)
    subprocess.run(cmd, check=True)


def resolve_lib(name: str, dirs: list[Path]) -> Path:
    candidates = []
    for d in dirs:
        for fmt in (f"{name}", f"lib{name}.a", f"{name}.lib",
                    f"{name}.LIB", f"lib{name}.lib"):
            candidates.append(d / fmt)
    base = Path(name)
    if base.is_file():
        return base.resolve()
    for c in candidates:
        if c.is_file():
            return c.resolve()
    # Default SDK archives.
    for d in (ROOT / "build/m6-sdk", ROOT / "build/m4-sdk"):
        for fmt in (f"{name}", f"{name}.lib", f"{name}.LIB",
                    f"lib{name}.a", f"lib{name}.lib"):
            c = d / fmt
            if c.is_file():
                return c.resolve()
    fail(f"cannot resolve library '{name}' (use -L DIR)")


def link_mode(sources: list[Path], out: Path, args):
    work = Path(tempfile.mkdtemp(prefix="tms-cc-"))
    try:
        copied = []
        for i, src in enumerate(sources):
            dst = work / f"c{i}.c"
            shutil.copyfile(src, dst)
            copied.append(dst)
        if not args.nostdlib:
            copied += [SHIM, HEAP]
        # Including the source directories preserves quoted headers.
        incs = ["-I", str(INCLUDE)]
        for d in sorted({str(s.parent) for s in sources} | set(args.includes)):
            if d not in incs:
                incs += ["-I", d]
        libs = [str(resolve_lib(n, [Path(x) for x in args.libdirs]))
                for n in args.libs]
        if not args.nostdlib:
            # The shim's %f path references flib's FD$* entries; link the SDK
            # runtimes by default, as the conformance harness does.
            for default in (ROOT / "build/m6-sdk/flib.lib",
                            ROOT / "build/m6-sdk/rts.lib"):
                if default.is_file():
                    libs.append(str(default))
        env = dict(os.environ)
        env.update({
            "M4_WORK": str(work),
            "M4_SDK": os.environ.get("M4_SDK", str(ROOT / "build/m4-sdk")),
            "M4_COFF": str(out),
            "M4_SOURCES": " ".join(str(s) for s in copied),
            "M4_ENTRY": str(ENTRY),
            "M4_NATIVE": "1",
            "M4_LINKER": "tms-link",
            "M4_SKIP_MAME": "1",
            "M4_CLANG_OPT": opt_level(args),
            "M4_LLC_OPT": "-O0",
            "M4_EXTRA_INCLUDES": " ".join(incs),
            "M4_NATIVE_PROG_LEN": args.prog_len,
            "M4_NATIVE_RAM_LEN": args.ram_len,
        })
        if args.g:
            env["M4_EXTRA_CFLAGS"] = "-g"
        if libs:
            env["M4_NATIVE_LIBS"] = " ".join(libs)
        # Prefer the direct 2ine assembler; fall back to DOSBox.
        lx = Path(os.environ.get(
            "M4_OS2_LX", Path.home() / "os2-work/2ine-tms34010/build/lx_loader"))
        if lx.is_file():
            env["M4_OS2"] = "1"
            env["M4_OS2_LX"] = str(lx)
        else:
            env["M4_OS2"] = "0"
        out.parent.mkdir(parents=True, exist_ok=True)
        cmd = [str(RUN_SH)]
        if args.verbose:
            print("+", " ".join(cmd), file=sys.stderr)
        r = subprocess.run(cmd, env=env)
        if r.returncode != 0:
            fail("link failed", r.returncode)
        # Keep a map next to the image.
        map_src = work / "m4.map"
        map_dst = Path(args.map) if args.map else out.with_suffix(".map")
        if map_src.is_file():
            shutil.copyfile(map_src, map_dst)
        if args.run:
            subprocess.run([str(ROOT / "scripts/tms-run"), str(out)], check=False)
    finally:
        if not args.keep:
            shutil.rmtree(work, ignore_errors=True)


def main(argv):
    ap = argparse.ArgumentParser(
        prog="tms-cc", description="Compile/link C for the TMS34010/VT1200 "
        "(freestanding; the conformance shim is the default runtime).")
    ap.add_argument("sources", nargs="+", help=".c source files")
    ap.add_argument("-o", "--output", help="output file")
    ap.add_argument("-c", action="store_true", help="compile to TI-COFF objects")
    ap.add_argument("-S", action="store_true", help="compile to GSPA assembly")
    ap.add_argument("-O0", dest="O0", action="store_true")
    ap.add_argument("-O", dest="opt", default="2")
    ap.add_argument("-g", action="store_true")
    ap.add_argument("-I", dest="includes", action="append", default=[])
    ap.add_argument("-L", dest="libdirs", action="append", default=[])
    ap.add_argument("-l", dest="libs", action="append", default=[])
    ap.add_argument("-nostdlib", action="store_true",
                    help="omit the shim/heap (user provides all symbols)")
    ap.add_argument("--text", default="018A0000")
    ap.add_argument("--bss", default="01A00000")
    ap.add_argument("--prog-len", default="40000h")
    ap.add_argument("--ram-len", default="80000h")
    ap.add_argument("--map", help="map output path")
    ap.add_argument("--run", action="store_true", help="run with tms-run")
    ap.add_argument("-v", "--verbose", action="store_true")
    ap.add_argument("--keep", action="store_true", help="keep the work directory")
    args = ap.parse_args(argv)

    sources = [Path(s) for s in args.sources]
    for s in sources:
        if not s.is_file():
            fail(f"source not found: {s}")
        if s.suffix not in (".c", ".C"):
            fail(f"not a C source: {s}")

    if args.c or args.S:
        if args.output and len(sources) > 1:
            outdir = Path(args.output)
            if not outdir.is_dir():
                fail("-o with multiple sources must be a directory")
        for src in sources:
            ext = ".o" if args.c else ".s"
            if args.output and len(sources) == 1:
                dst = Path(args.output)
            elif args.output:
                dst = Path(args.output) / (src.stem + ext)
            else:
                dst = src.with_suffix(ext)
            dst.parent.mkdir(parents=True, exist_ok=True)
            with tempfile.TemporaryDirectory(prefix="tms-cc-") as td:
                ir = Path(td) / "unit.ll"
                compile_ir(src, ir, opt_level(args), args)
                (llc_obj if args.c else llc_asm)(ir, dst, args)
            if args.verbose:
                print(dst)
        return 0

    if not TMS_LINK.is_file():
        fail(f"missing linker: {TMS_LINK}")
    if not ENTRY.is_file() or not SHIM.is_file():
        fail("missing conformance runtime files")
    out = Path(args.output or "a.coff")
    link_mode(sources, out, args)
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main(sys.argv[1:]))
    except subprocess.CalledProcessError as e:
        raise SystemExit(e.returncode)
