from __future__ import annotations

from datetime import datetime, timezone

import pytest

from argus.service.serving_spec import ServingSpec, resolve_serving_spec


def test_expand_home_macro_and_validate_user_path_ok():
    spec = ServingSpec(
        model_id="qwen-0.5b",
        model_source="$HOME/models/my_model",
        num_replicas=1,
        gpus_per_replica=1,
    )
    r = resolve_serving_spec(spec=spec, user_id="alice", now_utc=datetime(2026, 1, 6, 12, 35, tzinfo=timezone.utc))
    assert r.model_source == "/private/users/alice/models/my_model"
    assert r.model_id == "alice-202601061235-qwen-0.5b"


def test_expand_common_hf_macro_ok():
    spec = ServingSpec(
        model_id="qwen-0.5b",
        model_source="$HOME/common/hf/hub/models--Qwen--Qwen2.5/snapshots/abc",
        num_replicas=1,
        gpus_per_replica=1,
    )
    r = resolve_serving_spec(spec=spec, user_id="alice", now_utc=datetime(2026, 1, 6, 12, 35, tzinfo=timezone.utc))
    assert r.model_source.startswith("/private/hf/")


@pytest.mark.parametrize(
    "src",
    [
        "/etc/passwd",
        "relative/path",
        "/private/users/bob/models/x",
        "/private/users/alice/../bob/x",
        "/private/common/hf/x",
    ],
)
def test_model_source_path_rejected(src: str):
    spec = ServingSpec(model_id="qwen-0.5b", model_source=src, num_replicas=1, gpus_per_replica=1)
    with pytest.raises((ValueError, PermissionError)):
        resolve_serving_spec(spec=spec, user_id="alice", now_utc=datetime(2026, 1, 6, 12, 35, tzinfo=timezone.utc))

