"""Tests for requirements manager."""

import pytest
from pathlib import Path

from venvy.core.requirements_manager import (
    _parse_requirements,
    _write_requirements,
    remove_packages_from_requirements,
)


def test_parse_empty(tmp_path):
    req = tmp_path / "requirements.txt"
    req.write_text("")
    assert _parse_requirements(req) == {}


def test_parse_requirements(tmp_path):
    req = tmp_path / "requirements.txt"
    req.write_text("requests==2.31.0\nhttpx==0.27.0\n# comment\n")
    parsed = _parse_requirements(req)
    assert "requests" in parsed
    assert "httpx" in parsed
    assert parsed["requests"] == "requests==2.31.0"


def test_remove_packages(tmp_path):
    req = tmp_path / "requirements.txt"
    req.write_text("requests==2.31.0\nhttpx==0.27.0\n")
    remove_packages_from_requirements(["requests"], req)
    parsed = _parse_requirements(req)
    assert "requests" not in parsed
    assert "httpx" in parsed


def test_write_requirements_sorted(tmp_path):
    req = tmp_path / "requirements.txt"
    packages = {"zlib": "zlib==1.0", "aiohttp": "aiohttp==3.9.0"}
    _write_requirements(req, packages)
    lines = [l for l in req.read_text().splitlines() if l]
    assert lines[0].startswith("aiohttp")
    assert lines[1].startswith("zlib")
