"""Core tests for venvy."""
import json
import pytest
from pathlib import Path
from venvy.core.config import VenvyConfig, save_config, load_config, find_project_root
from venvy.core.requirements_manager import parse_requirements, write_requirements, remove_from_requirements


def test_config_roundtrip(tmp_path):
    cfg = VenvyConfig(venv_name=".venv", requirements_file="reqs.txt", install_ipykernel=True)
    save_config(cfg, tmp_path)
    loaded = load_config(tmp_path)
    assert loaded.venv_name == ".venv"
    assert loaded.requirements_file == "reqs.txt"
    assert loaded.install_ipykernel is True


def test_find_project_root_from_subdir(tmp_path):
    save_config(VenvyConfig(), tmp_path)
    subdir = tmp_path / "a" / "b"
    subdir.mkdir(parents=True)
    assert find_project_root(subdir) == tmp_path


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_write_requirements_sorted(tmp_path):
    req = tmp_path / "requirements.txt"
    pkgs = {"zlib": "zlib==1.0", "aiohttp": "aiohttp==3.9.0"}
    write_requirements(req, pkgs)
    lines = [l for l in req.read_text().splitlines() if l]
    assert lines[0].startswith("aiohttp")
    assert lines[1].startswith("zlib")


def test_remove_from_requirements(tmp_path):
    req = tmp_path / "requirements.txt"
    req.write_text("requests==2.31.0\nhttpx==0.27.0\n")
    # Patch console to avoid import issues
    import venvy.core.requirements_manager as rm
    rm.console = type("C", (), {"print": lambda *a, **k: None})()
    remove_from_requirements(["requests"], req)
    parsed = parse_requirements(req)
    assert "requests" not in parsed
    assert "httpx" in parsed


def test_hook_code_is_valid_python():
    """Ensure the injected hook code compiles without errors."""
    from venvy.core.hook import get_hook_files
    hook_py, hook_pth = get_hook_files()
    compile(hook_py, "<venvy_hook>", "exec")  # raises SyntaxError if broken
    assert "venvy_hook" in hook_pth
