"""Tests for artifact export service."""
import os
import tempfile
import zipfile
import io

import pytest

from src.domain.artifacts.service import ArtifactService


@pytest.mark.asyncio
async def test_export_source_zip():
    svc = ArtifactService()
    with tempfile.TemporaryDirectory() as tmpdir:
        with open(os.path.join(tmpdir, "index.html"), "w") as f:
            f.write("<html>hello</html>")
        os.makedirs(os.path.join(tmpdir, "css"))
        with open(os.path.join(tmpdir, "css", "style.css"), "w") as f:
            f.write("body { margin: 0; }")

        data = await svc.export_source_zip(tmpdir)
        assert len(data) > 0

        zf = zipfile.ZipFile(io.BytesIO(data))
        names = zf.namelist()
        assert "index.html" in names
        assert os.path.join("css", "style.css").replace("\\", "/") in [n.replace("\\", "/") for n in names]


@pytest.mark.asyncio
async def test_export_excludes_node_modules():
    svc = ArtifactService()
    with tempfile.TemporaryDirectory() as tmpdir:
        with open(os.path.join(tmpdir, "app.js"), "w") as f:
            f.write("console.log('hi')")
        nm = os.path.join(tmpdir, "node_modules", "pkg")
        os.makedirs(nm)
        with open(os.path.join(nm, "index.js"), "w") as f:
            f.write("module.exports = {}")

        data = await svc.export_source_zip(tmpdir)
        zf = zipfile.ZipFile(io.BytesIO(data))
        names = zf.namelist()
        assert "app.js" in names
        assert not any("node_modules" in n for n in names)
