"""
core/storage.py — the photos on this disk or in a bucket (MinIO). Pins the rules S3 would otherwise break
(see the module docstring): the arrival time survives every move, a failed move leaves the source where it was,
a folder never moves by halves, the index can be rebuilt from the bucket, the cache stays under its limit, and a
crash between "uploaded" and "deleted from incoming" never stores a photo twice.

Every test runs on the backend of the session (TEST_STORAGE=local|s3); those that only make sense for a bucket
are skipped on the local disk.
"""
import io
import os
import time
import zipfile

import pytest
from PIL import Image

from core import storage
from core.storage import Key
from conftest import DEMO_CODE, SCHOOL, insert_order, item

s3_only = pytest.mark.skipif(os.getenv("TEST_STORAGE", "local") != "s3", reason="bucket behaviour")


def _jpeg(color=(90, 30, 160)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", (300, 200), color).save(buf, "JPEG")
    return buf.getvalue()


# ── keys ───────────────────────────────────────────────────────────────────────

def test_a_key_cannot_leave_its_area():
    for bad in (("photos", "..", "x"), ("etc", "passwd"), ()):
        with pytest.raises(ValueError):
            storage.key(*bad)
    with pytest.raises(TypeError):
        storage.exists(storage.Path("photos/x.jpg"))          # a filesystem path is not a key
    assert storage.key("photos", "a", "b.jpg").area == "photos"


# ── the arrival time ───────────────────────────────────────────────────────────

def test_the_arrival_time_survives_a_move_the_trash_and_a_restore(isolated_storage):
    from services import photo_service
    old = time.time() - 40 * 86400
    k = storage.key("photos", "sc", "cam", "MAR-AAA-111", "a.jpg")
    storage.write_bytes(k, _jpeg(), mtime=old)
    moved = storage.key("photos", "sc", "cam", "MAR-AAA-111", "b.jpg")
    storage.move(k, moved)
    assert abs(storage.stat(moved).mtime - old) < 1
    assert photo_service.delete_photo("sc", "MAR-AAA-111", "b.jpg")
    entry = photo_service.list_trash("sc")[0]
    trashed = storage.walk(photo_service.trash_root("sc") / entry["id"])[0]
    assert abs(trashed.mtime - old) < 1                       # the trash does not restart the RGPD clock
    assert photo_service.restore_trash_entry("sc", entry["id"]) == 1
    assert abs(storage.stat(moved).mtime - old) < 1


def test_a_file_ingested_from_incoming_keeps_its_arrival_time(isolated_storage, tmp_path):
    src = tmp_path / "DSC_0001.JPG"
    src.write_bytes(_jpeg())
    t = time.time() - 3600
    os.utime(src, (t, t))
    k = storage.key("photos", "sc", "1A", "Student 1", "DSC_0001.JPG")
    storage.ingest(src, k)
    assert not src.exists() and abs(storage.stat(k).mtime - t) < 1
    assert storage.read_bytes(k)[:2] == b"\xff\xd8"


def test_a_trash_batch_ages_by_the_date_in_its_name(isolated_storage):
    from services import photo_service
    batch = photo_service.trash_root("sc") / "20200101-120000-photo-X"
    storage.write_bytes(batch / "1A" / "Student 1" / "a.jpg", _jpeg())       # a file written today
    assert photo_service._batch_age_days(batch) > 365                       # the batch is from 2020
    assert photo_service.purge_trash("sc", 30) == 1


# ── failures ───────────────────────────────────────────────────────────────────

@s3_only
def test_a_failed_copy_leaves_the_source_and_raises(isolated_storage, monkeypatch):
    src = storage.key("photos", "sc", "x", "a.jpg")
    storage.write_bytes(src, _jpeg())

    def broken(**kw):
        raise RuntimeError("connection reset")
    monkeypatch.setattr(isolated_storage.client, "copy_object", broken)
    with pytest.raises(storage.StorageError):
        storage.move(src, storage.key("photos", "sc", "y", "a.jpg"))
    assert storage.exists(src) and not storage.exists(storage.key("photos", "sc", "y", "a.jpg"))


@s3_only
def test_an_upload_that_is_not_verified_keeps_the_file_in_incoming(isolated_storage, monkeypatch, tmp_path):
    src = tmp_path / "DSC_0002.JPG"
    src.write_bytes(_jpeg())
    real_head = isolated_storage.client.head_object
    monkeypatch.setattr(isolated_storage.client, "head_object",
                        lambda **kw: {**real_head(**kw), "ContentLength": 1})          # truncated upload
    with pytest.raises(storage.StorageError):
        storage.ingest(src, storage.key("photos", "sc", "1A", "Student 1", "DSC_0002.JPG"))
    assert src.exists()


@s3_only
def test_a_folder_never_moves_by_halves(isolated_storage, monkeypatch):
    """A renamed class whose files moved half-way would point at a folder with half its photos."""
    src, dst = storage.key("photos", "sc", "CP A"), storage.key("photos", "sc", "CP B")
    for i in range(4):
        storage.write_bytes(src / "Student 1" / f"{i}.jpg", _jpeg())
    real_copy, calls = isolated_storage.client.copy_object, {"n": 0}

    def flaky(**kw):
        calls["n"] += 1
        if calls["n"] == 3:
            raise RuntimeError("bucket gone")
        return real_copy(**kw)
    monkeypatch.setattr(isolated_storage.client, "copy_object", flaky)
    with pytest.raises(storage.StorageError):
        storage.move_tree(src, dst)
    assert len(storage.walk(src)) == 4 and storage.walk(dst) == []


# ── index and cache ────────────────────────────────────────────────────────────

@s3_only
def test_reconcile_rebuilds_the_index_from_the_bucket(isolated_storage):
    from core.db import get_db
    k = storage.key("photos", "sc", "x", "kept.jpg")
    old = time.time() - 10 * 86400
    storage.write_bytes(k, _jpeg(), mtime=old)
    ghost = storage.key("photos", "sc", "x", "ghost.jpg")
    storage.write_bytes(ghost, _jpeg())
    isolated_storage.client.delete_object(Bucket=isolated_storage.bucket, Key=str(ghost))   # gone behind our back
    with get_db() as conn:
        conn.execute(f"DELETE FROM {isolated_storage.table}")                              # index lost
        conn.commit()
    assert storage.stat(k) is None
    out = storage.reconcile()
    assert out["added"] == 1 and storage.stat(ghost) is None
    assert abs(storage.stat(k).mtime - old) < 1, "the arrival time comes back from the object's metadata"


@s3_only
def test_the_cache_keeps_under_its_limit_and_serves_a_replaced_object_fresh(isolated_storage):
    cache = isolated_storage.cache
    cache.limit = 16 * 1024 * 1024
    big = os.urandom(3 * 1024 * 1024)
    keys = [storage.key("photos", "sc", "c", f"{i}.bin") for i in range(8)]
    for k in keys:
        storage.write_bytes(k, big)
        storage.local_path(k)
    cache.sweep()
    assert cache.size() <= cache.limit
    k = keys[0]
    storage.write_bytes(k, b"new content")
    assert storage.local_path(k).read_bytes() == b"new content"


@s3_only
def test_a_paid_download_does_not_go_through_the_cache(isolated_storage):
    k = storage.key("photos", "sc", "d", "hd.jpg")
    payload = _jpeg()
    storage.write_bytes(k, payload)
    isolated_storage.cache.forget(k)
    assert b"".join(storage.iter_chunks(k, 1000)) == payload
    assert not list(isolated_storage.cache.root.rglob("*.jpg"))


# ── organizer: a crash between upload and delete ───────────────────────────────

@s3_only
def test_after_a_crash_between_upload_and_delete_the_photo_is_not_stored_twice(isolated_storage, tmp_path):
    from services import organizer_service as O
    src = tmp_path / "DSC_0007.JPG"
    src.write_bytes(_jpeg())
    folder = storage.key("photos", "sc", "1A", "Student 1")
    storage.put_file(src, folder / src.name, mtime=src.stat().st_mtime)        # uploaded, then the server died
    org = O.PhotoOrganizer.__new__(O.PhotoOrganizer)
    org.school_id = "sc"
    assert org._move(src, folder / "DSC_0007_1.JPG")                         # what unique_name would hand out
    assert not src.exists()
    assert [f.name for f in storage.files(folder)] == ["DSC_0007.JPG"]


# ── downloads ──────────────────────────────────────────────────────────────────

async def test_the_order_zip_holds_the_exact_originals(client):
    oid = f"zip-{time.time_ns()}"
    insert_order(oid, DEMO_CODE, SCHOOL, [item(fmt="digital", photo="portrait.jpg", price=7.0),
                                          item(fmt="digital", photo="fratrie.jpg", price=7.0)])
    from services import media_service, photo_service
    r = await client.get(media_service.download_zip_url(oid))
    assert r.status_code == 200 and r.headers["content-type"] == "application/zip"
    z = zipfile.ZipFile(io.BytesIO(r.content))
    assert z.testzip() is None
    for name in ("portrait.jpg", "fratrie.jpg"):
        assert z.read(name) == storage.read_bytes(photo_service.find_photo(SCHOOL, DEMO_CODE, name))


async def test_a_single_paid_download_is_the_exact_original(client):
    oid = f"one-{time.time_ns()}"
    insert_order(oid, DEMO_CODE, SCHOOL, [item(fmt="digital", photo="portrait.jpg", price=7.0)])
    from services import media_service, photo_service
    r = await client.get(media_service.download_url(oid, "portrait.jpg"))
    assert r.status_code == 200 and "attachment" in r.headers["content-disposition"]
    original = storage.read_bytes(photo_service.find_photo(SCHOOL, DEMO_CODE, "portrait.jpg"))
    assert r.content == original and int(r.headers["content-length"]) == len(original)


# ── migration of the photos already on the disk ────────────────────────────────

@s3_only
def test_the_migration_uploads_with_the_arrival_time_and_frees_the_disk_only_when_asked(
        isolated_storage, tmp_path, monkeypatch, capsys):
    import sys as _sys
    from core import config
    sys_path = str(__import__("pathlib").Path(__file__).resolve().parent.parent / "scripts")
    monkeypatch.syspath_prepend(sys_path)
    import migrate_photos_to_s3 as M
    disk = tmp_path / "photos"
    photo = disk / "sc" / "1A" / "Student 1" / "a.jpg"
    photo.parent.mkdir(parents=True)
    photo.write_bytes(_jpeg())
    (disk / "sc" / "1A" / "Student 1" / ".protect").mkdir()
    (disk / "sc" / "1A" / "Student 1" / ".protect" / "a_heads_x.jpg").write_bytes(b"derivative")
    old = time.time() - 50 * 86400
    os.utime(photo, (old, old))
    monkeypatch.setattr(config, "PHOTOS_DIR", disk)
    monkeypatch.setattr(M.storage, "S3Storage", lambda: isolated_storage)

    monkeypatch.setattr(_sys, "argv", ["m"])
    assert M.main() == 0 and storage.walk(storage.key("photos")) == []          # dry run: nothing moved
    monkeypatch.setattr(_sys, "argv", ["m", "--apply"])
    assert M.main() == 0
    k = storage.key("photos", "sc", "1A", "Student 1", "a.jpg")
    assert abs(storage.stat(k).mtime - old) < 1 and photo.exists()
    assert not storage.exists(storage.key("photos", "sc", "1A", "Student 1", ".protect", "a_heads_x.jpg"))
    monkeypatch.setattr(_sys, "argv", ["m", "--apply", "--delete-local"])
    assert M.main() == 0 and not photo.exists()
    assert "0 archivo(s) subidos" in capsys.readouterr().out                 # re-run: already there
