"""Tests for the per-page extraction orchestrator.

extract_page_products() tries JSON-LD, then Open Graph meta, then the model,
and stops at the first source that yields anything.
"""
from unittest.mock import patch

from app.services.content import product_extraction as product_extraction

JSONLD_PAGE = {
    "url": "https://s.com/p/1", "title": "P1", "text": "some text",
    "jsonld": [{"@type": "Product", "name": "From JSON-LD",
                "offers": {"price": "10.00", "priceCurrency": "AUD"}}],
}
PLAIN_PAGE = {"url": "https://s.com/about", "title": "About", "text": "about us", "jsonld": []}


def test_jsonld_wins_and_the_model_is_never_called():
    """Paying for a model call when exact data is already on the page is waste."""
    with patch.object(product_extraction, "extract_with_llm") as llm:
        products = product_extraction.extract_page_products(JSONLD_PAGE, "", "org_x")
    llm.assert_not_called()
    assert products[0]["name"] == "From JSON-LD"


def test_falls_through_to_the_model_when_there_is_no_structured_data():
    with patch.object(product_extraction, "extract_with_llm",
                      return_value=[{"name": "From LLM"}]) as llm:
        products = product_extraction.extract_page_products(PLAIN_PAGE, "", "org_x")
    llm.assert_called_once()
    assert products[0]["name"] == "From LLM"


def test_a_failure_anywhere_returns_nothing_rather_than_raising():
    with patch.object(product_extraction, "extract_from_jsonld",
                      side_effect=RuntimeError("boom")):
        assert product_extraction.extract_page_products(JSONLD_PAGE, "", "org_x") == []
