import os
import time


def test_cleanup_partial_backups_removes_only_stale_zero_byte_files(tmp_path, monkeypatch):
    from services import db_backup_service as backup

    stale_zero = tmp_path / "momo_analytics_20260611_010050.sql.gz"
    fresh_zero = tmp_path / "momo_analytics_20260618_134900.sql.gz"
    normal_backup = tmp_path / "momo_analytics_20260618_020001.sql.gz"

    stale_zero.write_bytes(b"")
    fresh_zero.write_bytes(b"")
    normal_backup.write_bytes(b"ok")

    old_ts = time.time() - 7200
    os.utime(stale_zero, (old_ts, old_ts))

    monkeypatch.setattr(backup, "BACKUP_DIR", str(tmp_path))

    deleted = backup.cleanup_partial_backups(min_age_minutes=60)

    assert deleted == 1
    assert not stale_zero.exists()
    assert fresh_zero.exists()
    assert normal_backup.exists()


def test_cleanup_old_backups_counts_partial_cleanup(tmp_path, monkeypatch):
    from services import db_backup_service as backup

    stale_zero = tmp_path / "momo_analytics_20260611_010050.sql.gz"
    stale_zero.write_bytes(b"")
    old_ts = time.time() - 7200
    os.utime(stale_zero, (old_ts, old_ts))

    monkeypatch.setattr(backup, "BACKUP_DIR", str(tmp_path))
    monkeypatch.setattr(backup, "RETENTION_DAYS", 7)

    assert backup.cleanup_old_backups() == 1
    assert not stale_zero.exists()
