import tempfile
import unittest
from pathlib import Path

from litellm_detector.cli import build_parser
from litellm_detector.detector import scan


def _make_distribution(root: Path, version: str, with_suspicious_file: bool = False) -> None:
    metadata_dir = root / f"litellm-{version}.dist-info"
    metadata_dir.mkdir(parents=True)
    (metadata_dir / "METADATA").write_text(
        f"Metadata-Version: 2.1\nName: litellm\nVersion: {version}\n",
        encoding="utf-8",
    )
    (metadata_dir / "entry_points.txt").write_text(
        "[console_scripts]\nlitellm=litellm.main:run\n",
        encoding="utf-8",
    )

    package_dir = root / "litellm"
    package_dir.mkdir()
    (package_dir / "__init__.py").write_text("__version__ = 'x'\n", encoding="utf-8")
    if with_suspicious_file:
        (package_dir / "payload.sh").write_text("#!/bin/sh\necho hi\n", encoding="utf-8")


class DetectorTests(unittest.TestCase):
    def test_scan_finds_litellm_distribution(self) -> None:
        with tempfile.TemporaryDirectory() as tmp_dir:
            site_packages = Path(tmp_dir) / "lib" / "python3.11" / "site-packages"
            _make_distribution(site_packages, "1.80.0")

            findings = scan([tmp_dir])

            self.assertEqual(len(findings), 1)
            self.assertEqual(findings[0].version, "1.80.0")
            self.assertEqual(findings[0].status, "ok")
            self.assertEqual(findings[0].entry_points, ["litellm=litellm.main:run"])

    def test_scan_flags_known_advisory_versions(self) -> None:
        with tempfile.TemporaryDirectory() as tmp_dir:
            site_packages = Path(tmp_dir) / "site-packages"
            _make_distribution(site_packages, "1.62.0")

            findings = scan([str(site_packages)])

            self.assertEqual(len(findings), 1)
            self.assertEqual(findings[0].status, "warning")
            self.assertEqual(findings[0].advisories[0]["id"], "CVE-2025-11203")

    def test_scan_flags_suspicious_files(self) -> None:
        with tempfile.TemporaryDirectory() as tmp_dir:
            site_packages = Path(tmp_dir) / "dist-packages"
            _make_distribution(site_packages, "1.80.0", with_suspicious_file=True)

            findings = scan([str(site_packages)])

            self.assertEqual(len(findings), 1)
            self.assertEqual(findings[0].status, "warning")
            self.assertTrue(findings[0].suspicious_files[0].endswith("payload.sh"))

    def test_crawl_finds_nested_site_packages(self) -> None:
        with tempfile.TemporaryDirectory() as tmp_dir:
            site_packages = Path(tmp_dir) / "srv" / "app" / ".venv" / "lib" / "python3.12" / "site-packages"
            _make_distribution(site_packages, "1.80.0")

            findings = scan([tmp_dir], crawl=True)

            self.assertEqual(len(findings), 1)
            self.assertEqual(findings[0].version, "1.80.0")

    def test_parser_accepts_crawal_alias(self) -> None:
        parser = build_parser()
        args = parser.parse_args(["--crawal"])
        self.assertTrue(args.crawl)


if __name__ == "__main__":
    unittest.main()
