from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path

from .engine import SOLAR_VERSION, run_file, compile_to_python

# IMPORTANT: this is the *PyPI project name* you publish under (can be different than command name)
PYPIPKG = "solar-lang"


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(prog="solar")
    sub = p.add_subparsers(dest="cmd", required=True)

    r = sub.add_parser("run", help="Run a .solar script")
    r.add_argument("file", help="Path to .solar file")

    c = sub.add_parser("compile", help="Compile .solar to a standalone .py script")
    c.add_argument("file", help="Path to .solar file")
    c.add_argument("-o", "--out", help="Output .py path (default: same name with .py)")

    sub.add_parser("version", help="Show Solar version")
    sub.add_parser("help", help="Show help")


    return p


def main(argv: list[str] | None = None) -> int:
    if argv is None:
        argv = sys.argv[1:]

    parser = build_parser()
    ns = parser.parse_args(argv)

    if ns.cmd == "run":
        p = Path(ns.file)
        if not p.exists():
            print(f"solar: file not found: {p}", file=sys.stderr)
            return 2
        run_file(p)
        return 0

    if ns.cmd == "compile":
        p = Path(ns.file)
        if not p.exists():
            print(f"solar: file not found: {p}", file=sys.stderr)
            return 2
        out = compile_to_python(p, ns.out)
        print(out)
        return 0

    if ns.cmd == "version":
        print(SOLAR_VERSION)
        return 0

    if ns.cmd == "help":
        parser.print_help()
        return 0

    if ns.cmd == "update":
        return _cmd_update(force_user=bool(ns.user))

    parser.print_help()
    return 2


d

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