"""Tests for the Dependency Risk Analyzer."""

from contextguard.dependency import (
    DependencyAnalyzer,
    _levenshtein,
    _check_typosquatting,
    _parse_requirements,
)


class TestLevenshtein:
    def test_same_string(self):
        assert _levenshtein("hello", "hello") == 0

    def test_one_edit(self):
        assert _levenshtein("hello", "hallo") == 1

    def test_empty(self):
        assert _levenshtein("", "abc") == 3

    def test_completely_different(self):
        assert _levenshtein("abc", "xyz") == 3


class TestTyposquatting:
    def test_exact_match_no_warning(self):
        assert _check_typosquatting("requests") is None

    def test_similar_name(self):
        result = _check_typosquatting("requsets")  # typo
        assert result is not None
        assert "requests" in result

    def test_dissimilar_name(self):
        assert _check_typosquatting("my-unique-package-name") is None


class TestParseRequirements:
    def test_parse_simple(self, tmp_path):
        req = tmp_path / "requirements.txt"
        req.write_text("requests>=2.28\nflask==2.3.0\nnumpy\n")
        deps = _parse_requirements(req)
        assert len(deps) == 3
        assert deps[0] == ("requests", ">=2.28")
        assert deps[1] == ("flask", "==2.3.0")
        assert deps[2] == ("numpy", None)

    def test_skip_comments(self, tmp_path):
        req = tmp_path / "requirements.txt"
        req.write_text("# comment\nrequests\n  # another\nflask\n")
        deps = _parse_requirements(req)
        assert len(deps) == 2

    def test_missing_file(self, tmp_path):
        deps = _parse_requirements(tmp_path / "nonexistent.txt")
        assert deps == []


class TestDependencyAnalyzer:
    def test_audit_empty(self, tmp_path):
        req = tmp_path / "requirements.txt"
        req.write_text("")
        analyzer = DependencyAnalyzer(
            requirements_path=req,
            check_cves=False,
            check_pypi=False,
        )
        result = analyzer.audit()
        assert result.total_packages == 0

    def test_audit_offline(self, tmp_path):
        """Audit with network calls disabled."""
        req = tmp_path / "requirements.txt"
        req.write_text("requests>=2.28\nflask==2.3.0\n")
        analyzer = DependencyAnalyzer(
            requirements_path=req,
            check_cves=False,
            check_pypi=False,
            check_typosquatting=True,
        )
        result = analyzer.audit()
        assert result.total_packages == 2
        # requests and flask are actual popular names — no typosquatting
        for dep in result.dependencies:
            assert dep.typosquatting_warning is None
