"""Tests for the local package index."""

from __future__ import annotations

from pathlib import Path

import pytest

from mgf.fed import _index


@pytest.fixture
def local_index(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    d = tmp_path / "local-index"
    d.mkdir()
    monkeypatch.setattr(_index, "local_index_dir", lambda: d)
    return d


def test_list_local_empty(local_index: Path) -> None:
    assert _index.list_local() == {}


def test_list_local_parses_wheel_names(local_index: Path) -> None:
    (local_index / "mgf_common-0.46.7-py3-none-any.whl").touch()
    (local_index / "mgf_common-0.46.6-py3-none-any.whl").touch()
    (local_index / "mgf_vm_core-0.1.10-py3-none-any.whl").touch()
    (local_index / "not-a-wheel.txt").touch()
    assert _index.list_local() == {
        "mgf-common": ["0.46.6", "0.46.7"],
        "mgf-vm-core": ["0.1.10"],
    }


def test_publish_copies_into_index(local_index: Path, tmp_path: Path) -> None:
    src = tmp_path / "mgf_foo-1.0.0-py3-none-any.whl"
    src.write_bytes(b"wheel")
    dest = _index.publish(src)
    assert dest.parent == local_index and dest.read_bytes() == b"wheel"
    assert _index.list_local() == {"mgf-foo": ["1.0.0"]}


def test_resolve_args_order() -> None:
    args = _index.resolve_args(local=True)
    assert args[0] == "--find-links"  # local first
    assert "--index-url" in args and _index.CODEBERG_INDEX in args
    assert args.index("--find-links") < args.index("--index-url")
    assert _index.resolve_args(local=False)[0] == "--index-url"  # no find-links
