"""Pin-window helper — single source of truth for the mgf-common pin string.

Closes [PAPER-52](../../../../FEEDBACK.md) — catch-up onboarding text and
[PAPER-57](../../../../FEEDBACK.md) — federation-sync message both used to
hardcode a literal `>=0.X,<0.Y` window that went stale the moment mgf-common
crossed a MINOR. This module computes the window from `mgf.common.__version__`
so every caller stays in sync with the installed release.

Two helpers, one job:

- :func:`current_pin_window` returns ``">=0.38,<0.39"`` (or whatever matches
  the current package version's MAJOR.MINOR).
- :func:`pin_window_for_version` is the same, but accepts an explicit
  version string — useful for tests that pin behaviour without monkey-
  patching ``mgf.common.__version__``.

Both helpers return a **MINOR window** (``>=X.Y,<X.<Y+1>``), matching the
0.x discipline rule AP-03 — pin to a single MINOR, walk the pin forward
on each release.
"""

from __future__ import annotations

import mgf.common


def pin_window_for_version(version: str) -> str:
    """Return the canonical ``>=X.Y,<X.<Y+1>`` pin window for ``version``.

    The window is the **MINOR** that contains ``version`` (e.g.,
    ``"0.38.0"`` and ``"0.38.5"`` both yield ``">=0.38,<0.39"``).

    The output is the string a consumer would write into their
    ``pyproject.toml`` dependency stanza — quotes are the caller's
    business.

    If ``version`` cannot be parsed as ``MAJOR.MINOR[.PATCH...]``,
    falls back to ``">={version},<{version}+"`` so the caller still
    sees something resembling a pin (rather than a `ValueError`).
    The fallback is a diagnostic shape; production paths should
    fix the malformed version upstream.
    """
    parts = version.split(".")
    if len(parts) < 2:
        return f">={version},<{version}+"
    try:
        major = int(parts[0])
        minor = int(parts[1])
    except ValueError:
        return f">={version},<{version}+"
    return f">={major}.{minor},<{major}.{minor + 1}"


def current_pin_window() -> str:
    """Return the pin window for the currently-installed mgf-common.

    Equivalent to :func:`pin_window_for_version` ``(mgf.common.__version__)``.
    Use this in onboarding text, init-project pyproject snippets, and the
    federation-sync message so the pin stays in lockstep with the wheel
    that's actually being shipped.
    """
    return pin_window_for_version(mgf.common.__version__)


__all__ = [
    "current_pin_window",
    "pin_window_for_version",
]
