from __future__ import annotations

import argparse
import json

from e2e_automation_core import allure_summary, build_plan, inspect_accounts, latest_bugs, list_tests, run_pytest


def emit(payload) -> int:
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return int(payload.get("exit_code", 0)) if isinstance(payload, dict) else 0


def main() -> int:
    parser = argparse.ArgumentParser(description="Convenient agent entry for SaaS E2E automation")
    sub = parser.add_subparsers(dest="command", required=True)
    plan = sub.add_parser("plan")
    plan.add_argument("profile", nargs="?", default="standalone")
    run = sub.add_parser("run")
    run.add_argument("profile", nargs="?", default="standalone")
    run.add_argument("pytest_args", nargs=argparse.REMAINDER)
    tests = sub.add_parser("tests")
    tests.add_argument("--marker")
    sub.add_parser("accounts")
    bugs = sub.add_parser("bugs")
    bugs.add_argument("--limit", type=int, default=5)
    sub.add_parser("summary")

    args = parser.parse_args()
    if args.command == "plan":
        return emit(build_plan(args.profile))
    if args.command == "run":
        return emit(run_pytest(args.profile, args.pytest_args))
    if args.command == "tests":
        return emit(list_tests(args.marker))
    if args.command == "accounts":
        return emit(inspect_accounts())
    if args.command == "bugs":
        return emit(latest_bugs(args.limit))
    if args.command == "summary":
        return emit(allure_summary())
    raise AssertionError(args.command)


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