import pytest

from app.services.infra.database import bootstrap_tenant, get_db_connection
from app.services.enrichment.price_tiers import MIN_PRICED_PRODUCTS, compute_bands


def _insert(schema, rows):
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            for i, price in enumerate(rows):
                cur.execute(
                    f'INSERT INTO "{schema}".strategist_products '
                    "(product_key, name, product_url, price_cents) "
                    "VALUES (%s,%s,%s,%s)",
                    (f"t:{i}", f"P{i}", f"https://x.example/{i}", price))
        conn.commit()
    finally:
        conn.close()


@pytest.fixture
def priced(temp_tenant):
    bootstrap_tenant(temp_tenant)
    # 1..30 hundred: a known distribution so the percentiles are checkable.
    _insert(temp_tenant, [i * 100 for i in range(1, 31)])
    return temp_tenant


def test_bands_come_from_the_tenants_own_distribution(priced):
    low, high = compute_bands(priced)
    assert 900 <= low <= 1100      # around the 33rd percentile of 100..3000
    assert 2000 <= high <= 2200    # around the 67th


def test_too_few_products_yields_no_bands(temp_tenant):
    bootstrap_tenant(temp_tenant)
    _insert(temp_tenant, [100] * (MIN_PRICED_PRODUCTS - 1))
    assert compute_bands(temp_tenant) is None


def test_reference_price_is_preferred_over_source_price(temp_tenant):
    # A two-currency tenant must not be banded on unconverted numbers.
    bootstrap_tenant(temp_tenant)
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            for i in range(MIN_PRICED_PRODUCTS + 5):
                cur.execute(
                    f'INSERT INTO "{temp_tenant}".strategist_products '
                    "(product_key, name, product_url, price_cents, "
                    " price_reference_cents) VALUES (%s,%s,%s,%s,%s)",
                    (f"r:{i}", f"P{i}", f"https://x.example/r{i}", 999999, i * 100))
        conn.commit()
    finally:
        conn.close()

    low, high = compute_bands(temp_tenant)
    assert low < 999999 and high < 999999
