from __future__ import annotations
import argparse, json, sys
from .core import init as _init, setmodel as _setmodel, getmodel as _getmodel, ModelLoadError

def main():
    parser = argparse.ArgumentParser(prog="opennetwork", description="OpenNetwork Dev Suite CLI")
    sub = parser.add_subparsers(dest="cmd")

    p_init = sub.add_parser("init", help="Initialize and print quickstart banner")
    p_set = sub.add_parser("setmodel", help="Open the web playground")
    p_set.add_argument("--url", default=None, help="Override the playground URL")
    p_get = sub.add_parser("getmodel", help="Build a model from JSON and print a Keras summary")
    p_get.add_argument("path", help="Path to the model JSON")
    p_get.add_argument("--strict", action="store_true", help="Strict parsing (fail on unknowns)")
    p_get.add_argument("--no-auto-flatten", action="store_true", help="Disable auto-flatten before Dense")

    args = parser.parse_args()

    if args.cmd == "init":
        _init(verbose=True)
        return 0

    if args.cmd == "setmodel":
        _setmodel(url=args.url)
        return 0

    if args.cmd == "getmodel":
        try:
            model = _getmodel(args.path, strict=args.strict, auto_flatten=not args.no_auto_flatten)
            # Print summary to stdout
            model.summary()
            return 0
        except ModelLoadError as e:
            print(str(e), file=sys.stderr)
            return 2

    parser.print_help()
    return 0

if __name__ == "__main__":
    sys.exit(main())
