from app.services.content.website import extract_jsonld_blocks


def test_extracts_a_product_block():
    html = """
    <html><head>
      <script type="application/ld+json">
      {"@context":"https://schema.org","@type":"Product","name":"Blue Runner",
       "sku":"BR-42","offers":{"@type":"Offer","price":"129.00","priceCurrency":"AUD"}}
      </script>
    </head><body>hi</body></html>
    """
    blocks = extract_jsonld_blocks(html)
    assert len(blocks) == 1
    assert blocks[0]["@type"] == "Product"
    assert blocks[0]["sku"] == "BR-42"


def test_flattens_graph_wrapper():
    """Many sites wrap everything in @graph; the Product must still be reachable."""
    html = """
    <script type="application/ld+json">
    {"@context":"https://schema.org","@graph":[
      {"@type":"WebSite","name":"Shop"},
      {"@type":"Product","name":"Blue Runner"}]}
    </script>
    """
    types = [b.get("@type") for b in extract_jsonld_blocks(html)]
    assert "Product" in types and "WebSite" in types


def test_handles_a_list_at_the_top_level():
    html = '<script type="application/ld+json">[{"@type":"Product","name":"A"}]</script>'
    assert extract_jsonld_blocks(html)[0]["name"] == "A"


def test_bad_json_is_skipped_not_raised():
    """One broken block on a page must not lose the good ones."""
    html = ('<script type="application/ld+json">{not json}</script>'
            '<script type="application/ld+json">{"@type":"Product","name":"Good"}</script>')
    blocks = extract_jsonld_blocks(html)
    assert len(blocks) == 1 and blocks[0]["name"] == "Good"


def test_no_blocks_returns_empty_list():
    assert extract_jsonld_blocks("<html><body>nothing</body></html>") == []
