"""Tests for the price monitoring system."""

import time

import pytest

from agent_scout.price_monitor import PriceMonitor


@pytest.fixture
def monitor():
    return PriceMonitor(drop_threshold_pct=5.0)


def test_track_item(monitor):
    item = monitor.track("Laptop X", check_interval_seconds=1800)
    assert item.name == "Laptop X"
    assert item.check_interval_seconds == 1800
    items = monitor.get_tracked_items()
    assert len(items) == 1


def test_untrack_item(monitor):
    monitor.track("Laptop X")
    assert monitor.untrack("Laptop X") is True
    assert monitor.untrack("Nonexistent") is False
    assert len(monitor.get_tracked_items()) == 0


def test_add_alert(monitor):
    monitor.track("Laptop X")
    alert = monitor.add_alert("Laptop X", target_price=500.0, alert_type="below")
    assert alert is not None
    assert alert.target_price == 500.0
    assert alert.alert_type == "below"
    assert alert.active is True
    assert alert.triggered is False


def test_add_alert_nonexistent_item(monitor):
    alert = monitor.add_alert("Nonexistent", target_price=100.0)
    assert alert is None


def test_items_due_for_check(monitor):
    item = monitor.track("Laptop X", check_interval_seconds=0)  # always due
    assert item.last_checked == 0.0
    due = monitor.items_due_for_check()
    assert len(due) == 1
    assert due[0].name == "Laptop X"


def test_items_not_due(monitor):
    item = monitor.track("Laptop X", check_interval_seconds=9999)
    item.last_checked = time.time()  # just checked
    due = monitor.items_due_for_check()
    assert len(due) == 0


@pytest.mark.asyncio
async def test_record_price_no_db(monitor):
    monitor.track("Laptop X")
    changes = await monitor.record_price("Laptop X", 599.99, "Amazon")
    assert changes == []


@pytest.mark.asyncio
async def test_get_price_trend_no_db(monitor):
    trend = await monitor.get_price_trend("Laptop X")
    assert trend["trend"] == "unknown"
    assert trend["history"] == []


def test_track_with_sources(monitor):
    item = monitor.track("Phone Y", sources=["Amazon", "BestBuy"])
    assert item.sources == ["Amazon", "BestBuy"]


def test_multiple_alerts(monitor):
    monitor.track("Phone Y")
    monitor.add_alert("Phone Y", target_price=500.0, alert_type="below")
    monitor.add_alert("Phone Y", target_price=800.0, alert_type="above")
    item = monitor.get_tracked_items()[0]
    assert len(item.alerts) == 2
