"""Tests for Trigger model with offset_expr support."""

import polars as pl
import pytest
from pydantic import ValidationError
from tradepose_models.enums import OrderStrategy
from tradepose_models.strategy.trigger import Trigger


class TestTriggerOffsetExpr:
    """Tests for offset_expr field."""

    def test_trigger_with_offset_expr(self):
        """Trigger should accept offset_expr."""
        trigger = Trigger(
            name="sl",
            order_strategy=OrderStrategy.STOP_LOSS,
            priority=1,
            conditions=[pl.col("close") < pl.col("entry_price")],
            offset_expr=pl.col("atr"),
        )
        assert trigger.offset_expr is not None

    def test_trigger_offset_expr_is_required(self):
        """Trigger should reject when offset_expr is not set."""
        with pytest.raises(ValidationError) as exc_info:
            Trigger(
                name="sl",
                order_strategy=OrderStrategy.STOP_LOSS,
                priority=1,
                conditions=[],
            )
        assert "offset_expr" in str(exc_info.value)


class TestTriggerSerialization:
    """Tests for Trigger serialization with offset_expr."""

    def test_serialize_with_offset_expr(self):
        """Trigger with offset_expr should serialize correctly."""
        trigger = Trigger(
            name="trs",
            order_strategy=OrderStrategy.TRAILING_STOP,
            priority=1,
            conditions=[],
            offset_expr=pl.col("atr") * 2,
        )
        data = trigger.model_dump()
        assert data["offset_expr"] is not None

    def test_roundtrip_with_offset_expr(self):
        """Trigger with offset_expr should survive serialization roundtrip."""
        original = Trigger(
            name="trs",
            order_strategy=OrderStrategy.TRAILING_STOP,
            priority=1,
            conditions=[pl.col("bars_since_entry") > 3],
            offset_expr=pl.col("atr"),
        )
        data = original.model_dump()
        restored = Trigger.model_validate(data)

        assert restored.name == original.name
        assert restored.order_strategy == original.order_strategy
        assert restored.offset_expr is not None

    def test_serialize_literal_offset(self):
        """Trigger with literal offset should serialize correctly."""
        trigger = Trigger(
            name="entry",
            order_strategy=OrderStrategy.IMMEDIATE_ENTRY,
            priority=1,
            conditions=[pl.col("signal") == 1],
            offset_expr=pl.lit(0.0),  # Neutral strategies use 0.0
        )
        data = trigger.model_dump()
        assert data["offset_expr"] is not None
