"""Unit tests for the maintainer trust detector."""
from __future__ import annotations

from datetime import datetime, timedelta, timezone

from pyguard.detectors.maintainer import analyze_maintainer
from pyguard.models import PackageMetadata, PyPIRelease, Severity


def _release(version: str, days_ago: int) -> PyPIRelease:
    dt = datetime.now(tz=timezone.utc) - timedelta(days=days_ago)
    return PyPIRelease(version=version, upload_time=dt.strftime("%Y-%m-%dT%H:%M:%S"))


def test_new_package_under_7_days_is_high():
    meta = PackageMetadata(release_history=[_release("1.0.0", 3)])
    findings = analyze_maintainer("newpkg", "1.0.0", meta)
    sevs = {f.severity for f in findings}
    assert Severity.HIGH in sevs


def test_package_under_30_days_is_medium():
    meta = PackageMetadata(release_history=[_release("1.0.0", 20)])
    findings = analyze_maintainer("youngpkg", "1.0.0", meta)
    sevs = {f.severity for f in findings}
    assert Severity.MEDIUM in sevs


def test_old_package_no_age_finding():
    meta = PackageMetadata(release_history=[_release("1.0.0", 365)])
    findings = analyze_maintainer("oldpkg", "1.0.0", meta)
    age_findings = [f for f in findings if f.category == "maintainer_trust" and "old" in f.title.lower() or "new" in f.title.lower()]
    # No HIGH/CRITICAL from age alone
    assert not any(f.severity in (Severity.HIGH, Severity.CRITICAL) for f in age_findings)


def test_rapid_release_flagged():
    releases = [
        _release("1.0.0", 100),
        _release("1.0.1", 100),  # same day, minutes apart
    ]
    # Make second release only 30 minutes after first
    from datetime import datetime, timedelta, timezone
    base = datetime.now(tz=timezone.utc) - timedelta(days=100)
    releases[0] = PyPIRelease(version="1.0.0", upload_time=base.strftime("%Y-%m-%dT%H:%M:%S"))
    releases[1] = PyPIRelease(
        version="1.0.1",
        upload_time=(base + timedelta(minutes=30)).strftime("%Y-%m-%dT%H:%M:%S"),
    )
    meta = PackageMetadata(release_history=releases)
    findings = analyze_maintainer("fastpkg", "1.0.1", meta)
    assert any(f.severity == Severity.HIGH and "rapid" in f.title.lower() for f in findings)


def test_no_project_links_flagged():
    meta = PackageMetadata(release_history=[_release("1.0.0", 500)])
    findings = analyze_maintainer("nolinkspkg", "1.0.0", meta)
    assert any(f.category == "maintainer_trust" and "link" in f.title.lower() for f in findings)
