#!/usr/bin/env python3
"""Compare dated UK supermarket shelf prices. Python 3.10+, standard library only."""
import argparse
import csv
import io
import json
import os
import sys
from collections import defaultdict
from decimal import Decimal
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

SITE = "https://grocerystats.com"
SAMPLE = SITE + "/data/uk-supermarket-price-sample-2026-12-02.csv"


def download(url, api_key=None):
    headers = {"User-Agent": "GroceryStatsPythonExample/1.0", "Accept": "application/json" if api_key else "text/csv"}
    if api_key:
        headers["Authorization"] = "Bearer " + api_key
    with urlopen(Request(url, headers=headers), timeout=30) as response:
        data = response.read(5_000_001)
        if len(data) > 5_000_000:
            raise ValueError("Response exceeded the example's 5 MB limit.")
        return data.decode("utf-8-sig")


def compare_rows(rows):
    """The caller must supply one barcode-matched, size-checked pack at a time."""
    priced = [r for r in rows if r.get("price_gbp") is not None and Decimal(str(r["price_gbp"])) > 0]
    if not priced:
        raise ValueError("No positive shelf prices were returned.")
    return sorted(priced, key=lambda r: (Decimal(str(r["price_gbp"])), r["retailer"]))


def sample_groups(text):
    groups = defaultdict(list)
    for row in csv.DictReader(io.StringIO(text)):
        groups[row["gtin"]].append(row)  # Keep GTINs as strings, including leading zeroes.
    return groups


def barcode_rows(body):
    if body.get("pack_size_check") not in ("agree", "single_shop"):
        raise ValueError("Pack sizes conflict or could not be verified. Review the source listings before comparing.")
    return compare_rows(body.get("data", []))


def describe(identifier, rows):
    rows = compare_rows(rows)
    print(identifier + " | " + rows[0]["name"])
    for row in rows:
        price = Decimal(str(row["price_gbp"]))
        print(f"  {row['retailer']:12} £{price:.2f}  recorded {row['observed_on']}")
        print("    " + str(row.get("source_url", "")))
    if len({row["observed_on"] for row in rows}) > 1:
        print("  Observation dates differ. These are not simultaneous live quotes.", file=sys.stderr)
    if len({row["retailer"] for row in rows}) == 1:
        print("  One shop matched; there is no cross-shop comparison.")
    print("  Shelf prices only. Separate offers and membership conditions are not applied.\n")


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--sample", action="store_true", help="Free dated CSV, no key or credits (default)")
    mode.add_argument("--sample-file", help="Read an already downloaded sample CSV")
    mode.add_argument("--barcode", help="Live catalogue lookup: costs one API credit on success")
    args = parser.parse_args(argv)
    try:
        if args.barcode:
            if not args.barcode.isascii() or not args.barcode.isdigit() or len(args.barcode) not in (8, 12, 13, 14):
                raise ValueError("Use a GTIN of 8, 12, 13 or 14 digits. Shop-specific codes require retailer-scoped API lookup.")
            key = os.environ.get("GROCERY_API_KEY")
            if not key:
                raise ValueError("Set GROCERY_API_KEY in your environment. Do not put a key in source code.")
            body = json.loads(download(SITE + "/api/v1/products/barcode/" + args.barcode, key))
            describe(str(body["gtin"]), barcode_rows(body))
        else:
            if args.sample_file:
                with open(args.sample_file, encoding="utf-8-sig", newline="") as source:
                    text = source.read()
            else:
                text = download(SAMPLE)
            for gtin, rows in sample_groups(text).items():
                describe(gtin, rows)
        return 0
    except HTTPError as error:
        messages = {401: "The API key was rejected.", 402: "API credits are exhausted.", 404: "No listing or sample found.",
                    409: "The barcode is ambiguous within the retailer.", 429: "Rate limited. Retry after " + str(error.headers.get("Retry-After", "60")) + " seconds."}
        print(messages.get(error.code, f"Request failed with HTTP {error.code}."), file=sys.stderr)
    except (ValueError, KeyError, OSError, URLError) as error:
        print(str(error), file=sys.stderr)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
