import json
import os
import time
from pathlib import Path

import pytest

from pypos.modules.platform_ops.services.dr_backup_policy_service import DrBackupPolicyService

# edited by glg
pytestmark = [pytest.mark.unit]


def test_run_backup_with_manifest_and_checksum(tmp_path):
    source_file = tmp_path / "beta_sb_pos_sqlite.db"
    source_file.write_text("dummy-db", encoding="utf-8")
    missing_file = tmp_path / "missing.db"

    backup_root = tmp_path / "backups"
    service = DrBackupPolicyService(str(backup_root))
    result = service.run_backup(
        source_paths=[str(source_file), str(missing_file)],
        tag="daily",
    )

    assert Path(result["backup_dir"]).exists()
    assert len(result["copied_files"]) == 1
    assert len(result["missing_files"]) == 1
    copied = result["copied_files"][0]
    assert copied["size"] == source_file.stat().st_size
    assert len(copied["sha256"]) == 64

    manifest_path = Path(result["manifest_path"])
    assert manifest_path.exists()
    manifest_payload = json.loads(manifest_path.read_text(encoding="utf-8"))
    assert manifest_payload["backup_dir"] == result["backup_dir"]
    assert len(manifest_payload["copied_files"]) == 1


def test_prune_backups_respects_keep_and_age(tmp_path):
    source_file = tmp_path / "state.db"
    source_file.write_text("state", encoding="utf-8")

    backup_root = tmp_path / "backups"
    service = DrBackupPolicyService(str(backup_root))

    first = Path(service.run_backup(source_paths=[str(source_file)], tag="old-a")["backup_dir"])
    second = Path(service.run_backup(source_paths=[str(source_file)], tag="old-b")["backup_dir"])
    latest = Path(service.run_backup(source_paths=[str(source_file)], tag="newest")["backup_dir"])

    old_ts = time.time() - (3 * 24 * 3600)
    os.utime(first, (old_ts, old_ts))
    os.utime(second, (old_ts, old_ts))

    prune = service.prune_backups(keep_last=1, max_age_days=1)
    deleted = set(prune["deleted"])
    kept = set(prune["kept"])

    assert str(latest) in kept
    assert str(first) in deleted or str(second) in deleted
