#!/usr/bin/env python3

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from release_changelog import resolve_release_plan


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Resolve the next Wrkr release version deterministically from an "
            "explicit version or CHANGELOG.md Unreleased entries."
        )
    )
    parser.add_argument(
        "--repo-root",
        default=Path(__file__).resolve().parents[1],
        help="repository root to inspect (default: script parent repo root)",
    )
    parser.add_argument(
        "--release-version",
        help="explicit release version to normalize to vX.Y.Z",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="print a JSON object instead of the resolved version only",
    )
    return parser.parse_args()


def emit(payload: dict[str, str], as_json: bool) -> int:
    if as_json:
        print(json.dumps(payload, sort_keys=True))
    else:
        print(payload["version"])
    return 0


def main() -> int:
    args = parse_args()
    repo_root = Path(args.repo_root).resolve()

    try:
        payload = resolve_release_plan(repo_root, args.release_version)
        return emit(payload, args.json)
    except (RuntimeError, ValueError) as err:
        print(f"resolve_release_version: {err}", file=sys.stderr)
        return 1


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