# qsys/cli/io_cli.py
"""
Quick CLI: python -m qsys.cli.io_cli export-text myfile.ir
"""

import sys
from pathlib import Path


def _usage():
    print("Usage:")
    print("  python -m qsys.cli.io_cli export-text <circuit_pyfile> <out.ir>")
    print("  python -m qsys.cli.io_cli export-json <circuit_pyfile> <out.json>")
    print(
        "circuit_pyfile should define a variable `CIRCUIT` referencing a circuit object."
    )
    sys.exit(1)


def main(argv=None):
    import importlib.util
    from qsys.io import export_text, export_json

    argv = argv or sys.argv[1:]
    if len(argv) != 3:
        _usage()
    cmd, pyfile, out = argv
    pyfile = Path(pyfile).absolute()
    spec = importlib.util.spec_from_file_location("tmp_module", str(pyfile))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    if not hasattr(mod, "CIRCUIT"):
        print("pyfile must define CIRCUIT variable")
        sys.exit(2)
    circuit = mod.CIRCUIT
    if cmd == "export-text":
        export_text(circuit, out)
    elif cmd == "export-json":
        export_json(circuit, out)
    else:
        _usage()


if __name__ == "__main__":
    main()
