import io
import json
import zipfile

import pytest
from scripts.prepare_template_cloud_contract import extract_snapshot, prepare_checkout
from src.domain.templates.service import _with_cloud_access_files


@pytest.mark.parametrize("framework", ["nuxt_app", "react_app", "html"])
def test_seed_contract_preserves_design_and_is_repeatable(framework):
    original = {
        "app.vue": "<template>Existing design</template>",
        ".cursor/instructions.md": "Keep our visual style",
        ".env.example": "EXISTING_VAR=example\n",
    }
    files = _with_cloud_access_files(original, framework)
    assert files["app.vue"] == original["app.vue"]
    assert files[".cursor/instructions.md"].startswith("Keep our visual style")
    assert _with_cloud_access_files(files, framework) == files
    contract = json.loads(files["p2hs.platform.json"])
    assert contract["backend"]["local_database_allowed"] is False
    assert "Authorization" in contract["backend"]["rls"]["user_requests"]
    assert "public_url_env" not in contract["gateway"]
    assert "NUXT_PUBLIC_P2HS_GATEWAY_URL" not in files[".env.example"]
    assert "VITE_P2HS_GATEWAY_URL" not in files[".env.example"]
    assert "PROJECT_ID=" in files[".env.example"]


def test_custom_adapter_requires_explicit_migration(tmp_path):
    route = tmp_path / "server/api/records/[...path].ts"
    route.parent.mkdir(parents=True)
    original = "export default () => useStorage('records').getItem('all')"
    route.write_text(original)
    report = prepare_checkout(tmp_path, "nuxt_app")
    assert report["status"] == "needs_code_migration"
    assert route.read_text() == original
    assert "server/api/records/[...path].ts" in report["custom_adapter_conflicts"]


def test_archive_path_traversal_is_rejected(tmp_path):
    data = io.BytesIO()
    with zipfile.ZipFile(data, "w") as archive:
        archive.writestr("repo-sha/../../escape.txt", "no")
    with pytest.raises(ValueError, match="Unsafe"):
        extract_snapshot(data.getvalue(), tmp_path / "checkout")
