"""Tests for GET /snapshot.tar.gz — the in-memory source archive.

Required coverage:
  1. the route answers 200
  2. the response mimetype is application/gzip
  3. the body starts with the gzip magic bytes \\x1f\\x8b
  4. the archive is a real tar.gz holding the project source and none of the
     excluded artefacts (*.db, __pycache__, .git, .env, *.log, ...)
  5. building it writes nothing to disk
"""

from __future__ import annotations

import io
import os
import tarfile
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-snapshot-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")


@pytest.fixture()
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        yield c


def test_snapshot_returns_gzip_200(client):
    resp = client.get("/snapshot.tar.gz")

    assert resp.status_code == 200
    assert resp.mimetype == "application/gzip"
    assert resp.data.startswith(b"\x1f\x8b")
    assert "attachment" in resp.headers["Content-Disposition"]
    assert "jarvis-source.tar.gz" in resp.headers["Content-Disposition"]


def test_snapshot_contains_source_and_excludes_artefacts(client):
    resp = client.get("/snapshot.tar.gz")
    with tarfile.open(fileobj=io.BytesIO(resp.data), mode="r:gz") as tar:
        names = tar.getnames()
        contents = {n: tar.extractfile(n).read() for n in names if tar.getmember(n).isfile()}

    assert "app.py" in names
    assert "requirements.txt" in names
    assert ".gitignore" in names
    assert any(n.startswith("templates/") and n.endswith(".html") for n in names)
    assert any(n.startswith("orchestrator/") and n.endswith(".py") for n in names)

    for name in names:
        assert "__pycache__" not in name
        assert not name.startswith(".git/")
        assert not name.endswith((".db", ".db-wal", ".db-shm", ".pyc", ".log"))
        assert name != ".env"

    # the archive really is the current source, not a stale copy
    assert b"snapshot.tar.gz" in contents["app.py"]


def test_snapshot_writes_nothing_to_disk(client):
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    before = sorted(os.listdir(root))
    client.get("/snapshot.tar.gz")
    after = sorted(os.listdir(root))

    assert before == after
    assert not any(n.endswith((".tar.gz", ".tar", ".tgz")) for n in after)
