import shutil
from pathlib import Path
from uuid import uuid4

import pytest

from src.workers.project_setup_pipeline import (
    _assert_import_supported,
    _collect_env_values,
    _copy_import_tree,
)


def _workspace_tmp() -> Path:
    root = Path("tests_tmp_project_github_import") / uuid4().hex
    root.mkdir(parents=True)
    return root


def test_github_import_collects_env_values_and_skips_env_files():
    root = _workspace_tmp()
    source = root / "source"
    source.mkdir()
    (source / ".env").write_text(
        "API_TOKEN=secret\nVITE_PUBLIC_URL=https://example.test\n",
        encoding="utf-8",
    )
    (source / ".env.production").write_text("STRIPE_SECRET_KEY=sk_test\n", encoding="utf-8")
    (source / ".env.example").write_text("API_TOKEN=\n", encoding="utf-8")
    (source / "index.html").write_text("<h1>Hello</h1>\n", encoding="utf-8")

    entries = _collect_env_values(str(source))
    by_key = {(e["key"], e["environment"]): e for e in entries}

    assert by_key[("API_TOKEN", "all")]["visibility"] == "secret"
    assert by_key[("VITE_PUBLIC_URL", "all")]["visibility"] == "public"
    assert by_key[("STRIPE_SECRET_KEY", "production")]["value"] == "sk_test"

    try:
        dest = root / "dest"
        _copy_import_tree(str(source), str(dest))
        assert (dest / "index.html").exists()
        assert not (dest / ".env").exists()
        assert not (dest / ".env.production").exists()
        assert (dest / ".env.example").exists()
    finally:
        shutil.rmtree(root, ignore_errors=True)


def test_github_import_rejects_submodules_and_lfs():
    root = _workspace_tmp()
    source = root / "source"
    source.mkdir()
    try:
        (source / ".gitmodules").write_text("[submodule]\n", encoding="utf-8")
        with pytest.raises(RuntimeError, match="submodules"):
            _assert_import_supported(str(source))

        (source / ".gitmodules").unlink()
        (source / ".gitattributes").write_text(
            "*.png filter=lfs diff=lfs merge=lfs -text\n",
            encoding="utf-8",
        )
        with pytest.raises(RuntimeError, match="LFS"):
            _assert_import_supported(str(source))
    finally:
        shutil.rmtree(root, ignore_errors=True)

