import argparse, sys, json
from .scrapers.runner import run_all, run_one
from .scheduler import scheduler_get, scheduler_set
from .policy import get_policy, set_policy

def main():
    p = argparse.ArgumentParser(prog="dvc_brokers_scraper")
    sub = p.add_subparsers(dest="cmd", required=True)

    r = sub.add_parser("run")
    r.add_argument("--broker")

    s = sub.add_parser("schedule")
    s.add_argument("action", choices=["get", "set"])
    s.add_argument("cron", nargs="?")

    c = sub.add_parser("crawl-policy")
    c.add_argument("action", choices=["get", "set"])
    c.add_argument("path", nargs="?")

    sub.add_parser("status")

    args = p.parse_args()
    if args.cmd == "run":
        print(json.dumps(run_one(args.broker) if args.broker else run_all()))
    elif args.cmd == "schedule":
        if args.action == "get":
            print(scheduler_get())
        else:
            assert args.cron, "cron required"
            scheduler_set(args.cron)
            print(json.dumps({"ok": True, "cron": args.cron}))
    elif args.cmd == "crawl-policy":
        if args.action == "get":
            print(json.dumps(get_policy(), indent=2))
        else:
            assert args.path, "path to json required"
            set_policy(json.loads(open(args.path).read()))
            print(json.dumps({"ok": True}))
    elif args.cmd == "status":
        from .scrapers.runner import latest_status
        print(json.dumps(latest_status()))
    else:
        p.print_help()

if __name__ == "__main__":
    main()
