"""Contract tests for Market resource against the live API."""

from __future__ import annotations

import pytest

from cardog import Cardog
from cardog.types.market import (
    MarketAnalysis,
    MarketBreakdown,
    MarketGeography,
    MarketOdometer,
    MarketOverview,
    MarketPosition,
    MarketPricing,
    MarketPulse,
    MarketTrends,
)


@pytest.mark.contract
class TestMarketContracts:
    """Validate Market endpoint response shapes match our Pydantic models."""

    def test_overview_returns_valid_response(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.overview(test_make, test_model, test_year)
        assert isinstance(result, MarketOverview)
        assert result.vehicle
        assert result.total_listings >= 0
        assert result.avg_price >= 0
        assert result.median_price >= 0
        assert result.min_price <= result.max_price
        assert result.q1_price <= result.q3_price

    def test_pricing_returns_distribution(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.pricing(test_make, test_model, test_year)
        assert isinstance(result, MarketPricing)
        assert isinstance(result.distribution, list)
        if result.distribution:
            bucket = result.distribution[0]
            assert bucket.bucket_min >= 0
            assert bucket.bucket_max >= bucket.bucket_min
            assert bucket.count >= 0

    def test_breakdown_returns_trims(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.breakdown(test_make, test_model, test_year)
        assert isinstance(result, MarketBreakdown)
        assert result.vehicle
        assert result.total_listings >= 0
        assert isinstance(result.trims, list)
        if result.trims:
            trim = result.trims[0]
            assert trim.listings >= 0
            assert trim.avg_price >= 0

    def test_odometer_returns_segments(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.odometer(test_make, test_model, test_year)
        assert isinstance(result, MarketOdometer)
        assert isinstance(result.segments, list)
        if result.segments:
            seg = result.segments[0]
            assert seg.odometer_min >= 0
            assert seg.listings >= 0
            assert seg.avg_price >= 0

    def test_geography_returns_markets(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.geography(test_make, test_model, test_year)
        assert isinstance(result, MarketGeography)
        assert isinstance(result.markets, list)
        if result.markets:
            market = result.markets[0]
            assert market.state
            assert market.listings >= 0
            assert market.avg_price >= 0

    def test_trends_returns_time_series(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.trends(test_make, test_model, test_year)
        assert isinstance(result, MarketTrends)
        assert isinstance(result.trends, list)
        if result.trends:
            point = result.trends[0]
            assert point.period
            assert point.new_listings >= 0

    def test_trends_with_period(
        self, client: Cardog, test_make: str, test_model: str, test_year: int
    ):
        result = client.market.trends(test_make, test_model, test_year, period="month")
        assert isinstance(result, MarketTrends)

    def test_analysis_by_vin(self, client: Cardog, test_vin: str):
        result = client.market.analysis(test_vin)
        assert isinstance(result, MarketAnalysis)
        assert isinstance(result.similar_listings, list)
        assert result.price_analysis is not None
        assert result.price_analysis.count >= 0

    def test_pulse_returns_overview(self, client: Cardog):
        result = client.market.pulse()
        assert isinstance(result, MarketPulse)
        assert result.overview.total_listings >= 0
        assert result.overview.avg_price >= 0
        assert isinstance(result.price_distribution, list)
        assert isinstance(result.make_distribution, list)

    def test_pulse_with_filters(self, client: Cardog):
        result = client.market.pulse(
            active_only=True,
            max_top_makes=5,
            max_top_models=3,
        )
        assert isinstance(result, MarketPulse)
        assert len(result.make_distribution) <= 5

    def test_position_for_listing(self, client: Cardog):
        # Get a listing first
        search = client.listings.search(limit=1)
        if not search.listings:
            pytest.skip("No listings available")
        listing_id = search.listings[0].id

        result = client.market.position(listing_id)
        assert isinstance(result, MarketPosition)
        assert result.id == listing_id
        assert result.price >= 0

    def test_treemap(self, client: Cardog):
        result = client.market.treemap()
        assert isinstance(result, (list, dict))

    def test_treemap_by_make(self, client: Cardog, test_make: str):
        result = client.market.treemap(test_make)
        assert isinstance(result, (list, dict))
