"""Tests for ServerContext (#82 Phase 2a).

ServerContext is a small dataclass that holds per-session state. Phase
2a itself is behavior-neutral; this test suite just pins down the
contract that Phase 2b will rely on:

    - Construction from explicit fields.
    - Default-factory mutability for `activity`.
    - `current_session` defaults to None and is freely assignable.
    - Each ServerContext has an independent `activity` (no shared
      SessionActivity instance across contexts — protects against the
      mutable-default footgun if the dataclass is ever edited).
"""
from __future__ import annotations

from pathlib import Path

import pytest

from active_claude_github_mcp.context import ServerContext
from active_claude_github_mcp.utils import SessionActivity


def _make_ctx(**overrides) -> ServerContext:
    base = dict(
        config=object(),
        github_token="gh_token",
        anthropic_api_key="anthropic_key",
        project_dir=Path("/tmp/does-not-exist"),
    )
    base.update(overrides)
    return ServerContext(**base)


def test_construction_populates_required_fields():
    ctx = _make_ctx()
    assert ctx.github_token == "gh_token"
    assert ctx.anthropic_api_key == "anthropic_key"
    assert ctx.project_dir == Path("/tmp/does-not-exist")


def test_current_session_defaults_to_none_and_is_assignable():
    ctx = _make_ctx()
    assert ctx.current_session is None
    ctx.current_session = {"session_id": "abc"}
    assert ctx.current_session == {"session_id": "abc"}


def test_activity_defaults_to_fresh_session_activity():
    ctx = _make_ctx()
    assert isinstance(ctx.activity, SessionActivity)
    assert ctx.activity.turns_posted == 0
    assert ctx.activity.turns_by_thread == {}


def test_each_context_has_independent_activity():
    """Guards against the mutable-default-argument footgun if someone
    ever rewrites the dataclass field to `activity: SessionActivity =
    SessionActivity()`."""
    ctx_a = _make_ctx()
    ctx_b = _make_ctx()
    ctx_a.activity.turns_posted += 1
    assert ctx_a.activity.turns_posted == 1
    assert ctx_b.activity.turns_posted == 0
    assert ctx_a.activity is not ctx_b.activity


def test_activity_mutations_persist_on_same_context():
    ctx = _make_ctx()
    ctx.activity.discussions_created += 2
    ctx.activity.turns_by_thread["D_123"] = 5
    assert ctx.activity.discussions_created == 2
    assert ctx.activity.turns_by_thread == {"D_123": 5}


def test_explicit_activity_override_is_honored():
    custom = SessionActivity(turns_posted=7)
    ctx = _make_ctx(activity=custom)
    assert ctx.activity is custom
    assert ctx.activity.turns_posted == 7
