"""The local package index — the always-available dependency source.

``release-local`` (Phase 2) builds a wheel, validates it, and **publishes it here**;
dependents in later waves then resolve their mgf-* deps from it without touching
Codeberg. Same version number as the eventual remote (build-once): a local release of
``vX`` is the identical artifact later *promoted* to Codeberg.

Resolution precedence (Q2): the local index (``--find-links``) alongside Codeberg, then
public PyPI. pip/uv pick the highest available version across sources, so a locally-released
version that is *ahead* of remote wins — matching "local may lead; remote is the mirror".
"""

from __future__ import annotations

import re
import shutil
from pathlib import Path

_WHEEL_RE = re.compile(r"^(?P<name>[A-Za-z0-9_.]+?)-(?P<ver>[0-9][^-]*)-.*\.whl$")

CODEBERG_INDEX = "https://codeberg.org/api/packages/magogi-admin/pypi/simple/"
PYPI_INDEX = "https://pypi.org/simple/"


def local_index_dir() -> Path:
    d = Path.home() / ".mgf" / "local-index"
    d.mkdir(parents=True, exist_ok=True)
    return d


def list_local() -> dict[str, list[str]]:
    """``{normalized package name: sorted versions}`` currently in the local index."""
    out: dict[str, set[str]] = {}
    for whl in local_index_dir().glob("*.whl"):
        m = _WHEEL_RE.match(whl.name)
        if m:
            out.setdefault(m["name"].replace("_", "-").lower(), set()).add(m["ver"])
    return {k: sorted(v) for k, v in sorted(out.items())}


def resolve_args(*, local: bool = True, remote: bool = True) -> list[str]:
    """pip/uv resolution args.

    ``local`` adds the local index (``--find-links``). ``remote`` adds Codeberg as the primary
    index. With ``remote=False`` (the local-release smoke), Codeberg is omitted: mgf-* deps must
    resolve from the **local index** (third-party still from PyPI) — which enforces wave order,
    since a dependent can only smoke-install once its deps are locally released.
    """
    args: list[str] = []
    if local:
        args += ["--find-links", str(local_index_dir())]
    if remote:
        args += ["--index-url", CODEBERG_INDEX, "--extra-index-url", PYPI_INDEX]
    else:
        args += ["--index-url", PYPI_INDEX]
    return args


def publish(wheel: Path) -> Path:
    """Copy a built wheel into the local index (idempotent). Returns the destination."""
    dest = local_index_dir() / Path(wheel).name
    shutil.copy2(wheel, dest)
    return dest


def run_local_index() -> int:
    d = local_index_dir()
    pkgs = list_local()
    print(f"local index: {d}  ({len(pkgs)} packages)")
    for name, vers in pkgs.items():
        print(f"  {name:<24} {', '.join(vers)}")
    print("\nresolve order: local find-links → Codeberg → public PyPI")
    print("(release-local publishes wheels here; dependents resolve from it first)")
    return 0
