"""Tests for per-user/workspace session policy resolution."""

from __future__ import annotations

import json
from dataclasses import dataclass

from ieum.server.session_policy import SessionPolicyResolver


@dataclass
class _DummyConfig:
    session_policy_file: str | None = None
    default_approval_policy: str = "manual"
    session_timeout_minutes: int = 60
    max_sessions_per_user: int = 0
    session_rate_limit_max_requests: int = 0
    session_rate_limit_window_seconds: int = 60
    sandbox_root: str | None = None


def test_resolve_defaults_without_policy_file() -> None:
    resolver = SessionPolicyResolver(_DummyConfig())
    policy = resolver.resolve(user_id="u1", workspace_id="w1")

    assert policy.approval_policy == "manual"
    assert policy.timeout_minutes == 60
    assert policy.max_concurrent_sessions is None
    assert policy.rate_limit_max_requests is None
    assert policy.rate_limit_window_seconds == 60
    assert policy.sandbox_root is None


def test_resolve_merges_user_workspace_overrides(temp_dir) -> None:
    policy_file = f"{temp_dir}/session_policy.json"
    content = {
        "defaults": {
            "approval_policy": "read_only",
            "timeout_minutes": 30,
            "max_concurrent_sessions": 2,
        },
        "users": {
            "alice": {
                "approval_policy": "safe_write",
            }
        },
        "workspaces": {
            "proj": {
                "timeout_minutes": 10,
            }
        },
        "user_workspaces": {
            "alice/proj": {
                "approval_policy": "full_trusted",
                "rate_limit_max_requests": 5,
                "rate_limit_window_seconds": 15,
                "sandbox_root": f"{temp_dir}/sandbox",
            }
        },
    }
    with open(policy_file, "w", encoding="utf-8") as fp:
        json.dump(content, fp)

    resolver = SessionPolicyResolver(_DummyConfig(session_policy_file=policy_file))
    policy = resolver.resolve(user_id="alice", workspace_id="proj")

    assert policy.approval_policy == "full_trusted"
    assert policy.timeout_minutes == 10
    assert policy.max_concurrent_sessions == 2
    assert policy.rate_limit_max_requests == 5
    assert policy.rate_limit_window_seconds == 15
    assert policy.sandbox_root is not None
    assert policy.sandbox_root.endswith("/sandbox")
