from __future__ import annotations

import argparse
import sys

from .compiler import CompileError, compile_file


def main() -> int:
    parser = argparse.ArgumentParser(
        prog="sophi",
        description="Sophi language compiler - generates portable validity proofs.",
    )
    sub = parser.add_subparsers(dest="command")

    compile_p = sub.add_parser("compile", help="Compile a .sph file into a proof")
    compile_p.add_argument("file", help="Path to .sph source file")
    compile_p.add_argument("-o", "--out", help="Write proof JSON to a file instead of stdout")

    args = parser.parse_args()

    if args.command != "compile":
        parser.print_help()
        return 2

    try:
        compiled = compile_file(args.file)
    except CompileError as exc:
        print(str(exc), file=sys.stderr)
        return 1

    output = compiled.to_json()
    if args.out:
        with open(args.out, "w", encoding="utf-8") as f:
            f.write(output)
    else:
        print(output)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
