"""Database copies off the server (backup_service): encrypted, read back, really restorable, pruned safely."""
import contextlib
import gzip
import uuid
from datetime import datetime, timedelta, timezone

import boto3
import pytest
from cryptography.fernet import Fernet
from moto import mock_aws

from core import config
from core.db import get_db
from services import alert_service, backup_service as b


@pytest.fixture
def offsite(monkeypatch, tmp_path):
    # With TEST_STORAGE=s3 the whole suite already runs inside moto: a second mock would wipe its bucket.
    guard = contextlib.nullcontext() if config.STORAGE_BACKEND == "s3" else mock_aws()
    with guard:
        bucket = f"bk-{uuid.uuid4().hex[:12]}"
        client = boto3.client("s3", region_name="us-east-1", aws_access_key_id="testing", aws_secret_access_key="testing")
        client.create_bucket(Bucket=bucket)
        for k, v in {"S3_ENDPOINT_URL": "", "S3_ACCESS_KEY": "testing", "S3_SECRET_KEY": "testing", "S3_REGION": "us-east-1",
                     "BACKUP_S3_BUCKET": bucket, "BACKUP_ENCRYPTION_KEY": Fernet.generate_key().decode()}.items():
            monkeypatch.setattr(config, k, v)
        monkeypatch.setattr(b, "BACKUPS_DIR", tmp_path)
        with get_db() as conn:
            conn.execute("DELETE FROM app_kv WHERE key=?", (b._KV_STATUS,))
            conn.commit()
        yield client, bucket


def _keys(client, bucket):
    return [o["Key"] for o in client.list_objects_v2(Bucket=bucket).get("Contents", [])]


def test_a_copy_is_encrypted_read_back_and_really_restores(app, offsite):
    client, bucket = offsite
    marker = f"marker-{uuid.uuid4().hex}"
    with get_db() as conn:
        conn.execute("INSERT OR REPLACE INTO app_kv (key, value) VALUES (?,?)", ("test:backup", f"{marker}; it's\nback\\slash"))
        conn.commit()
    b.run_once()
    keys = _keys(client, bucket)
    assert len(keys) == 1 and keys[0].startswith("db-backups/") and keys[0].endswith(".sql.gz.enc")
    blob = client.get_object(Bucket=bucket, Key=keys[0])["Body"].read()
    assert marker.encode() not in blob and blob[:2] != b"\x1f\x8b"      # not a readable gzip
    status = b.get_status()
    assert status["last_ok_at"] and not status["last_error"] and status["restore_ok_at"] and not status["restore_error"]
    dump = b.fetch_offsite(keys[0].split("/")[1])
    assert marker in gzip.decompress(dump).decode()
    with get_db() as conn:                                     # the throwaway database did not stay
        assert not conn.execute("SELECT 1 FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=?",
                                (f"{config.MYSQL_DB}_restore_check",)).fetchone()
        conn.execute("DELETE FROM app_kv WHERE key='test:backup'")
        conn.commit()


def test_the_wrong_key_or_an_altered_copy_is_refused(app, offsite, monkeypatch):
    client, bucket = offsite
    dump = b._backup_once()
    name = b.upload_offsite(dump, client)["name"]
    good_key = config.BACKUP_ENCRYPTION_KEY
    monkeypatch.setattr(config, "BACKUP_ENCRYPTION_KEY", Fernet.generate_key().decode())
    with pytest.raises(b.BackupError):
        b.fetch_offsite(name, client)
    monkeypatch.setattr(config, "BACKUP_ENCRYPTION_KEY", good_key)
    client.put_object(Bucket=bucket, Key=f"db-backups/{name}", Body=b"garbage", Metadata={"sha256": "0" * 64})
    with pytest.raises(b.BackupError):
        b.fetch_offsite(name, client)


def test_a_truncated_dump_is_never_sent(app, offsite, tmp_path):
    client, bucket = offsite
    bad = tmp_path / "meeconic_20260101_0000.sql.gz"
    bad.write_bytes(gzip.compress(b"SET NAMES utf8mb4;\nDROP TABLE x;\n"))
    with pytest.raises(b.BackupError):
        b.upload_offsite(bad, client)
    assert _keys(client, bucket) == []


def test_without_the_key_nothing_leaves_and_the_team_is_told(app, offsite, monkeypatch):
    client, bucket = offsite
    monkeypatch.setattr(config, "BACKUP_ENCRYPTION_KEY", "")
    monkeypatch.setattr(config, "STORAGE_BACKEND", "s3")
    sent = []
    monkeypatch.setattr(alert_service, "notify", lambda key, *a, **k: sent.append(key))
    b.run_once()
    assert _keys(client, bucket) == [] and "backup-offsite-off" in sent
    assert list(b.BACKUPS_DIR.glob("meeconic_*.sql.gz"))       # the local copy is still made


def test_a_failed_upload_alerts_and_deletes_nothing(app, offsite, monkeypatch):
    client, bucket = offsite
    old = "meeconic_20200101_0000.sql.gz.enc"
    client.put_object(Bucket=bucket, Key=f"db-backups/{old}", Body=b"x")
    sent = []
    monkeypatch.setattr(alert_service, "notify", lambda key, *a, **k: sent.append(key))
    monkeypatch.setattr(b, "upload_offsite", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("MinIO down")))
    b.run_once()
    assert "backup-offsite-failed" in sent and f"db-backups/{old}" in _keys(client, bucket)
    assert "MinIO down" in b.get_status()["last_error"]


def test_retention_keeps_48h_then_one_per_day_and_always_the_newest():
    now = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc)
    name = lambda d: f"meeconic_{d.strftime('%Y%m%d_%H%M')}.sql.gz.enc"   # noqa: E731
    recent = [name(now - timedelta(hours=h)) for h in range(0, 47)]
    day5 = [name(datetime(2026, 11, 18, h, 0, tzinfo=timezone.utc)) for h in (3, 9, 20)]
    ancient = name(now - timedelta(days=30))
    drop = set(b.names_to_delete(recent + day5 + [ancient, "notes.txt"], now, 14))
    assert drop == {day5[0], day5[1], ancient}
    assert b.names_to_delete([ancient], now, 14) == []         # backups stopped: the last one is never deleted


def test_this_disk_keeps_one_copy_a_day_while_the_bucket_keeps_the_hourly_ones(app, offsite):
    now = b.utcnow().replace(tzinfo=timezone.utc)
    for h in range(1, 6):
        (b.BACKUPS_DIR / f"meeconic_{(now - timedelta(days=3, hours=h)).strftime('%Y%m%d_%H%M')}.sql.gz").write_bytes(b"x")
    for h in range(1, 6):
        (b.BACKUPS_DIR / f"meeconic_{(now - timedelta(minutes=h)).strftime('%Y%m%d_%H%M')}.sql.gz").write_bytes(b"x")
    b._purge_old()
    left = [b._stamp(f.name).date() for f in b.BACKUPS_DIR.glob("meeconic_*.sql.gz")]
    assert len(left) == len(set(left))                         # never two copies of the same day on the disk
