"""ICE Report Center API client.

Discovers report download URLs via the private JSON API at
https://www.ice.com/marketdata/api/reports/293/results
No authentication required. Results are date-descending.
"""

ICE_API_URL = "https://www.ice.com/marketdata/api/reports/293/results"
ICE_BASE_URL = "https://www.ice.com"
PRODUCT_ID_COFFEE = 2
API_TIMEOUT_SECONDS = 30
MAX_API_PAGES = 10


def fetch_report_listings(session, product_id, max_results=50, page_number=1) -> list[dict]:
    """POST to ICE API and return normalized report rows.

    Each row: {publish_date, product_name, download_url, download_label}
    """
    assert product_id > 0, f"product_id must be positive, got {product_id}"
    assert max_results > 0, f"max_results must be positive, got {max_results}"
    assert page_number > 0, f"page_number must be positive, got {page_number}"

    payload = {
        "offset": (page_number - 1) * max_results,
        "pageNumber": page_number,
        "productId": product_id,
        "max": max_results,
    }
    response = session.post(
        ICE_API_URL,
        data=payload,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
        timeout=API_TIMEOUT_SECONDS,
    )
    assert response.status_code == 200, (
        f"ICE API returned {response.status_code}"
    )

    data = response.json()
    rows = data["datasets"]["results"]["rows"]

    result = []
    for row in rows:
        download = row.get("download", {}) or {}
        url = download.get("url", "") or ""
        if url and not url.startswith("http"):
            url = ICE_BASE_URL + url
        result.append({
            "publish_date": row.get("publishDate", ""),
            "product_name": row.get("productName", ""),
            "download_url": url,
            "download_label": download.get("label", "") or "",
        })

    return result


def find_all_reports(session, label_substring, max_pages=MAX_API_PAGES, product_id=PRODUCT_ID_COFFEE) -> list[dict]:
    """Return all reports whose download_label contains label_substring.

    Paginates up to max_pages. Results are date-descending.
    """
    assert label_substring, "label_substring must not be empty"
    assert max_pages > 0, f"max_pages must be positive, got {max_pages}"

    found = []
    for page in range(1, max_pages + 1):
        rows = fetch_report_listings(session, product_id, page_number=page)
        if not rows:
            break
        for row in rows:
            if label_substring.lower() in row["download_label"].lower():
                found.append(row)

    return found


def find_latest_report(session, label_substring, product_id=PRODUCT_ID_COFFEE) -> dict | None:
    """Return first report whose download_label contains label_substring.

    Paginates up to MAX_API_PAGES. Results are date-descending so
    the first match is the most recent.
    """
    assert label_substring, "label_substring must not be empty"

    for page in range(1, MAX_API_PAGES + 1):
        rows = fetch_report_listings(session, product_id, page_number=page)
        if not rows:
            break
        for row in rows:
            if label_substring.lower() in row["download_label"].lower():
                return row

    return None
