"""Tests para parse_amazon_ranking_html (parser puro de rankings Amazon)."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from datascience.parse_amazon_ranking_html import parse_amazon_ranking_html

# Fixture: dos cards estilo grid 2026 (gridItemRoot) con badge de rank,
# data-asin, titulo, precio y rating. La segunda lleva un badge de pct_change
# tipo movers ('zg-percent-change') para validar ese campo.
_GRID_HTML = """
<div class="p13n-desktop-grid">
  <div id="gridItemRoot" class="a-column a-span12 a-text-center">
    <div class="a-cardui p13n-grid-content">
      <div data-asin="B0D49Y53FS">
        <div class="zg-bdg-ctr"><span class="zg-bdg-text">#1</span></div>
        <div class="zg-percent-change">+150%</div>
        <div class="zg-grid-general-faceout">
          <div class="p13n-sc-uncoverable-faceout">
            <a class="a-link-normal aok-block" href="/Sun-Shade/dp/B0D49Y53FS/ref=zg_bs_1?psc=1">
              <img alt="Sun Shade Car Protector Folding Umbrella" />
            </a>
            <div class="_cDEzb_p13n-sc-css-line-clamp-3_g3dy1">Sun Shade Car Protector Folding Umbrella</div>
            <div class="a-icon-row">
              <a class="a-link-normal" href="/product-reviews/B0D49Y53FS">
                <i class="a-icon a-icon-star-small"><span class="a-icon-alt">4.0 out of 5 stars</span></i>
                <span class="a-size-small">666</span>
              </a>
            </div>
            <span class="a-price"><span class="a-offscreen">&euro;13.95</span></span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="gridItemRoot" class="a-column a-span12 a-text-center">
    <div class="a-cardui p13n-grid-content">
      <div data-asin="B0GXZDZRS5">
        <div class="zg-bdg-ctr"><span class="zg-bdg-text">#2</span></div>
        <div class="zg-percent-change">-30%</div>
        <div class="zg-grid-general-faceout">
          <div class="p13n-sc-uncoverable-faceout">
            <a class="a-link-normal aok-block" href="/Emergency-Light/dp/B0GXZDZRS5/ref=zg_bs_2?psc=1">
              <img alt="GSC Emergency Light V16 Geolocation" />
            </a>
            <div class="_cDEzb_p13n-sc-css-line-clamp-3_g3dy1">GSC Emergency Light V16 Geolocation</div>
            <div class="a-icon-row">
              <a class="a-link-normal" href="/product-reviews/B0GXZDZRS5">
                <i class="a-icon a-icon-star-small"><span class="a-icon-alt">4.6 out of 5 stars</span></i>
                <span class="a-size-small">24</span>
              </a>
            </div>
            <span class="a-price"><span class="a-offscreen">&euro;15.90</span></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
"""


def test_parsea_dos_cards_con_todos_los_campos():
    rows = parse_amazon_ranking_html(
        _GRID_HTML, marketplace="amazon.es", list_type="bestsellers", max_items=50
    )
    assert len(rows) == 2
    first = rows[0]
    assert first["rank"] == 1
    assert first["asin"] == "B0D49Y53FS"
    assert "Sun Shade" in first["title"]
    assert first["price"] == 13.95
    assert first["currency"] == "EUR"
    assert first["rating"] == 4.0
    assert first["reviews"] == 666
    assert first["url"] == "https://www.amazon.es/Sun-Shade/dp/B0D49Y53FS/ref=zg_bs_1"
    assert first["marketplace"] == "amazon.es"
    assert first["list_type"] == "bestsellers"


def test_contrato_de_claves_exacto():
    rows = parse_amazon_ranking_html(_GRID_HTML, marketplace="amazon.es")
    expected = {
        "marketplace", "list_type", "category", "rank", "asin", "title",
        "price", "currency", "rating", "reviews", "pct_change", "url",
    }
    assert set(rows[0].keys()) == expected


def test_pct_change_solo_en_movers_shakers():
    # En bestsellers pct_change siempre es None aunque el badge exista.
    bs = parse_amazon_ranking_html(_GRID_HTML, list_type="bestsellers")
    assert bs[0]["pct_change"] is None
    assert bs[1]["pct_change"] is None
    # En movers_shakers se parsea: +150% y -30%.
    mv = parse_amazon_ranking_html(_GRID_HTML, list_type="movers_shakers")
    assert mv[0]["pct_change"] == 150.0
    assert mv[1]["pct_change"] == -30.0


def test_html_vacio_devuelve_lista_vacia():
    assert parse_amazon_ranking_html("") == []
    assert parse_amazon_ranking_html("<html><body><p>nada</p></body></html>") == []


def test_max_items_limita_resultados():
    rows = parse_amazon_ranking_html(_GRID_HTML, max_items=1)
    assert len(rows) == 1
    assert rows[0]["rank"] == 1
