"""
Tests for submit packaging behavior.
"""

from __future__ import annotations

import zipfile
from pathlib import Path

from torivers_sdk.cli.commands.submit import _create_package


def _write_file(path: Path, content: str = "x") -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content)


def test_create_package_excludes_cache_and_gitignored_files(
    tmp_path: Path, monkeypatch
) -> None:
    """Packager should exclude static patterns and project .gitignore patterns."""
    # Included files
    _write_file(tmp_path / "automation.yaml", "name: demo\nversion: 1.0.0\n")
    _write_file(tmp_path / "main.py", "print('ok')\n")
    _write_file(tmp_path / "nodes" / "process.py", "def run(): pass\n")

    # Static exclusions
    _write_file(tmp_path / "__pycache__" / "main.cpython-313.pyc")
    _write_file(tmp_path / ".venv" / "bin" / "python")
    _write_file(tmp_path / ".pytest_cache" / "state")
    _write_file(tmp_path / ".env.local", "SECRET=1\n")
    _write_file(tmp_path / "runtime.log", "log\n")
    _write_file(tmp_path / ".DS_Store", "junk\n")

    # .gitignore-driven exclusions
    _write_file(
        tmp_path / ".gitignore",
        ".ruff_cache/\n.python-version\n.custom-cache/\n",
    )
    _write_file(tmp_path / ".ruff_cache" / "cache.db")
    _write_file(tmp_path / ".python-version", "3.13\n")
    _write_file(tmp_path / ".custom-cache" / "artifact.tmp")

    monkeypatch.chdir(tmp_path)
    package_path = _create_package()
    assert package_path is not None

    with zipfile.ZipFile(package_path) as zf:
        names = set(zf.namelist())

    package_path.unlink()

    # Included
    assert "automation.yaml" in names
    assert "main.py" in names
    assert "nodes/process.py" in names

    # Excluded by static defaults
    assert "__pycache__/main.cpython-313.pyc" not in names
    assert ".venv/bin/python" not in names
    assert ".pytest_cache/state" not in names
    assert ".env.local" not in names
    assert "runtime.log" not in names
    assert ".DS_Store" not in names
    assert ".gitignore" not in names

    # Excluded by .gitignore patterns
    assert ".ruff_cache/cache.db" not in names
    assert ".python-version" not in names
    assert ".custom-cache/artifact.tmp" not in names
