"""Tests for temporal='current' write-through (#1286).

Verifies that temporal='current' is explicitly stored rather than silently
dropped by _add_claim().
"""

from __future__ import annotations

from unittest.mock import AsyncMock, MagicMock, patch

import pytest


def _make_candidate(temporal: str = "current", **overrides):
    """Build a minimal CandidateClaim-like object."""
    defaults = {
        "subject": "Andrew",
        "predicate": "lives in",
        "object_value": "Bangkok",
        "confidence": 0.9,
        "sensitivity": "normal",
        "category": "identity",
        "temporal": temporal,
        "temporal_marker": None,
        "intrinsic_type": "fact",
        "human_family": None,
        "memory_class": "semantic",
        "event_date": None,
        "sequence_order": None,
        "salience": "medium",
        "status": "active",
        "cause": None,
        "effect": None,
        "state_before": None,
        "state_after": None,
        "explicitness": "explicit",
        "stability": "stable",
        "scope_entity_id": None,
        "scope_entity_type": None,
        "metadata": None,
    }
    defaults.update(overrides)
    obj = MagicMock()
    for k, v in defaults.items():
        setattr(obj, k, v)
    return obj


@pytest.mark.asyncio
async def test_temporal_current_is_stored():
    """temporal='current' must be explicitly written to kwargs, not dropped."""
    from cortex.core.reconciliation.storage_helpers import StorageHelpersMixin

    mock_storage = AsyncMock()
    mock_claim = MagicMock()
    mock_claim.id = "claim-123"
    mock_storage.create_claim = AsyncMock(return_value=mock_claim)

    mock_config = MagicMock()
    mock_config.session_confidence_default = 0.5

    helpers = StorageHelpersMixin.__new__(StorageHelpersMixin)
    helpers.storage = mock_storage
    helpers.config = mock_config
    helpers._record_provenance = AsyncMock()

    candidate = _make_candidate(temporal="current")

    await helpers._add_claim(
        candidate=candidate,
        session_id="test-session",
        owner_id="owner-1",
    )

    mock_storage.create_claim.assert_called_once()
    call_kwargs = mock_storage.create_claim.call_args
    # temporal="current" must be in the kwargs, NOT dropped
    all_kwargs = call_kwargs.kwargs if call_kwargs.kwargs else {}
    # Also check positional kwargs dict
    if not all_kwargs and len(call_kwargs.args) > 3:
        # Passed as **kwargs expansion
        pass
    # The create_claim call uses keyword arguments
    _, kw = call_kwargs
    assert kw.get("temporal") == "current", (
        f"temporal='current' was dropped! Got kwargs: {kw}"
    )


@pytest.mark.asyncio
async def test_temporal_past_is_stored():
    """temporal='past' should still be stored (regression check)."""
    from cortex.core.reconciliation.storage_helpers import StorageHelpersMixin

    mock_storage = AsyncMock()
    mock_claim = MagicMock()
    mock_claim.id = "claim-456"
    mock_storage.create_claim = AsyncMock(return_value=mock_claim)

    mock_config = MagicMock()
    mock_config.session_confidence_default = 0.5

    helpers = StorageHelpersMixin.__new__(StorageHelpersMixin)
    helpers.storage = mock_storage
    helpers.config = mock_config
    helpers._record_provenance = AsyncMock()

    candidate = _make_candidate(temporal="past")

    await helpers._add_claim(
        candidate=candidate,
        session_id="test-session",
        owner_id="owner-1",
    )

    _, kw = mock_storage.create_claim.call_args
    assert kw.get("temporal") == "past"


@pytest.mark.asyncio
async def test_temporal_none_is_not_stored():
    """temporal=None should not add temporal key to kwargs."""
    from cortex.core.reconciliation.storage_helpers import StorageHelpersMixin

    mock_storage = AsyncMock()
    mock_claim = MagicMock()
    mock_claim.id = "claim-789"
    mock_storage.create_claim = AsyncMock(return_value=mock_claim)

    mock_config = MagicMock()
    mock_config.session_confidence_default = 0.5

    helpers = StorageHelpersMixin.__new__(StorageHelpersMixin)
    helpers.storage = mock_storage
    helpers.config = mock_config
    helpers._record_provenance = AsyncMock()

    candidate = _make_candidate(temporal=None)

    await helpers._add_claim(
        candidate=candidate,
        session_id="test-session",
        owner_id="owner-1",
    )

    _, kw = mock_storage.create_claim.call_args
    assert "temporal" not in kw, f"temporal=None should not be stored, got: {kw.get('temporal')}"
