from __future__ import annotations

import importlib.util
from importlib.machinery import SourceFileLoader
import os
import subprocess
from pathlib import Path


WORKER = Path(__file__).resolve().parents[2] / "sandbox/image/bin/cdx-k3s-worker"


def test_worker_git_commands_trust_only_the_configured_workspace(monkeypatch):
    loader = SourceFileLoader("cdx_k3s_worker", str(WORKER))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    assert spec is not None and spec.loader is not None
    worker = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(worker)
    workspace = Path("/workspace")
    calls = []
    monkeypatch.setattr(worker, "WORKSPACE", workspace)
    monkeypatch.setattr(
        worker, "call",
        lambda argv, **_kwargs: calls.append(argv) or subprocess.CompletedProcess(argv, 0),
    )

    worker.git("status")

    assert calls == [[
        "/usr/bin/git", "-c", "safe.directory=/workspace", "-C", "/workspace", "status",
    ]]


def test_worker_uploads_captured_result_even_when_agent_exits_nonzero(tmp_path):
    workspace = tmp_path / "workspace"
    result = tmp_path / "result"
    workspace.mkdir()
    result.mkdir()
    subprocess.run(["/usr/bin/git", "init", "-q", str(workspace)], check=True)
    subprocess.run(["/usr/bin/git", "-C", str(workspace), "config", "user.name", "fixture"], check=True)
    subprocess.run(["/usr/bin/git", "-C", str(workspace), "config", "user.email", "fixture@example.invalid"], check=True)
    (workspace / "value.txt").write_text("before\n")
    subprocess.run(["/usr/bin/git", "-C", str(workspace), "add", "value.txt"], check=True)
    subprocess.run(["/usr/bin/git", "-C", str(workspace), "commit", "-qm", "base"], check=True)
    base = subprocess.check_output(["/usr/bin/git", "-C", str(workspace), "rev-parse", "HEAD"], text=True).strip()
    agent = tmp_path / "agent"
    agent.write_text(f"#!/bin/sh\nprintf 'after\\n' > {workspace / 'value.txt'}\nexit 17\n")
    agent.chmod(0o755)
    uploader = tmp_path / "uploader"
    uploader.write_text("#!/bin/sh\ntest -s \"$1\"\ntouch \"$1.uploaded\"\n")
    uploader.chmod(0o755)
    env = {
        **os.environ,
        "CDX_WORKSPACE": str(workspace),
        "CDX_RESULT_DIR": str(result),
        "CDX_RESULT_UPLOADER": str(uploader),
    }

    completed = subprocess.run([str(WORKER), base, "--", str(agent)], env=env, check=False)

    assert completed.returncode == 17
    bundle = result / "result.bundle"
    assert bundle.is_file()
    assert bundle.with_suffix(".bundle.uploaded").is_file()
    verified = subprocess.run(
        ["/usr/bin/git", "-C", str(workspace), "bundle", "verify", str(bundle)],
        text=True, capture_output=True, check=False,
    )
    assert verified.returncode == 0, verified.stderr
