from __future__ import annotations

from pathlib import Path

import agent_preflight as package

from agent_preflight.docker import run_container


class TestRunContainer:
    def test_uses_temp_env_file_and_accepts_string_mounts(self, monkeypatch, tmp_path):
        captured = {}

        def fake_provision_key(_admin_key, _label, _limit_usd):
            return "sk-or-test-subkey"

        def fake_remove_container(_name):
            return None

        def fake_popen(cmd, **kwargs):
            captured["cmd"] = cmd

            env_file = cmd[cmd.index("--env-file") + 1]
            captured["env_file"] = env_file
            captured["env_file_contents"] = Path(env_file).read_text()
            raise RuntimeError("stop after command build")

        monkeypatch.setattr("agent_preflight.docker.provision_key", fake_provision_key)
        monkeypatch.setattr("agent_preflight.docker.remove_container", fake_remove_container)
        monkeypatch.setattr("agent_preflight.docker.subprocess.Popen", fake_popen)
        monkeypatch.setattr("agent_preflight.docker.get_usage", lambda _key: 0.0)

        result = run_container(
            image_name="test-image:latest",
            model_id="z-ai/glm-5",
            alias="writer",
            admin_key="admin",
            budget_usd=0.05,
            run_dir=tmp_path,
            run_id="run-123",
            env={"FOO": "bar"},
            mounts=[
                ("/host/task.md", "/workspace/task.md", "ro"),
                "/host/cache:/workspace/cache:delegated",
            ],
        )

        cmd = captured["cmd"]
        assert "--env-file" in cmd
        assert "-e" not in cmd
        assert "OPENROUTER_API_KEY=sk-or-test-subkey" not in " ".join(cmd)
        assert "OPENROUTER_API_KEY=sk-or-test-subkey" in captured["env_file_contents"]
        assert "FOO=bar" in captured["env_file_contents"]
        assert "/host/task.md:/workspace/task.md:ro" in cmd
        assert "/host/cache:/workspace/cache:delegated" in cmd
        assert not Path(captured["env_file"]).exists()
        assert result.cost_usd == 0.0
        assert result.error == "stop after command build"

    def test_package_level_provision_key_patch_is_used(self, monkeypatch, tmp_path):
        captured = {}

        monkeypatch.setattr(package, "provision_key", lambda *_args, **_kwargs: "sk-or-package-level")
        monkeypatch.setattr(package, "get_usage", lambda _key: 0.0)
        monkeypatch.setattr("agent_preflight.docker.remove_container", lambda _name: None)

        def fake_popen(cmd, **kwargs):
            captured["cmd"] = cmd
            env_file = cmd[cmd.index("--env-file") + 1]
            captured["env_file_contents"] = Path(env_file).read_text()
            raise RuntimeError("stop after command build")

        monkeypatch.setattr("agent_preflight.docker.subprocess.Popen", fake_popen)

        result = run_container(
            image_name="test-image:latest",
            model_id="z-ai/glm-5",
            alias="writer",
            admin_key="admin",
            budget_usd=0.05,
            run_dir=tmp_path,
            run_id="run-123",
        )

        assert "OPENROUTER_API_KEY=sk-or-package-level" in captured["env_file_contents"]
        assert result.error == "stop after command build"
