"""Legal, free sources of product images.

1. Open Icecat (manufacturer-approved). Brands such as HP, Lenovo and others publish official product photos
   for their resellers through Open Icecat. Lookup is exact, by Brand + manufacturer part number (MPN) or GTIN/EAN
   barcode, so the photo is guaranteed to be the right product. Register free at icecat.biz to get a username
   (and optionally an app key). Icecat's fair-use policy requires an "AS IS" disclaimer, which the storefront shows.

2. Wikimedia Commons (free licences). Only CC0, public domain, CC BY and CC BY-SA files are accepted, and the
   author credit and licence are stored with each image and shown on the product page. Because Commons search is
   fuzzy, candidates are saved to a review folder first; you delete wrong matches, then import the rest.
"""
import html
import re
import time

import requests

UA = "ProductImageFetcher/1.0 (shop catalogue; contact via site) python-requests"
# Commercial use allowed: CC0, public domain, CC BY, CC BY-SA. Anything non-commercial (NC) or no-derivatives (ND)
# is rejected because a shop is commercial use and we resize/convert images.
ALLOWED_LICENCES = re.compile(r"^(cc0( \d\.\d)?|public domain( mark)?( \d\.\d)?|pd(-[\w.-]+)?|cc by( \d\.\d)?( [a-z]{2,3})?|cc by-sa( \d\.\d)?( [a-z]{2,3})?)$", re.I)


def licence_ok(lic):
    lic = (lic or "").strip()
    if re.search(r"\b(nc|nd)\b|non-?commercial|no ?deriv", lic, re.I):
        return False
    return bool(ALLOWED_LICENCES.match(lic))


def _get(url, params=None, timeout=30):
    r = requests.get(url, params=params, headers={"User-Agent": UA}, timeout=timeout)
    r.raise_for_status()
    return r


def download(url):
    return _get(url, timeout=60).content


# ---------------------------------------------------------------- Open Icecat

def icecat_images(username, brand=None, mpn=None, gtin=None, app_key=None, limit=5):
    """Return {"title", "images": [url...], "credit"} or None if the product isn't in Open Icecat."""
    params = {"lang": "EN", "shopname": username, "content": "gallery,essentialinfo,title"}
    if app_key:
        params["app_key"] = app_key
    if gtin:
        params["GTIN"] = gtin
    elif brand and mpn:
        params.update({"Brand": brand, "ProductCode": mpn.upper()})
    else:
        return None
    try:
        data = _get("https://live.icecat.biz/api", params=params).json()
    except (requests.RequestException, ValueError):
        return None
    d = (data or {}).get("data") or {}
    gallery = d.get("Gallery") or []
    urls = []
    for g in sorted(gallery, key=lambda g: (0 if str(g.get("IsMain", "")).upper() in ("Y", "TRUE", "1") else 1, g.get("No", 99))):
        u = g.get("Pic") or g.get("Pic500x500") or g.get("HighPic") or g.get("LowPic")
        if u and u not in urls:
            urls.append(u if u.startswith("http") else "https:" + u)
        if len(urls) >= limit:
            break
    if not urls:
        return None
    gi = d.get("GeneralInfo") or {}
    title = gi.get("Title") or (gi.get("TitleInfo") or {}).get("GeneratedIntTitle") or ""
    brand_name = gi.get("Brand") or brand or ""
    return {"title": title, "images": urls,
            "credit": {"source": "icecat", "text": f"Image © {brand_name}, provided by Open Icecat (AS IS)",
                       "link": "https://icecat.biz", "license": "Open Icecat Open Content License"}}


# ---------------------------------------------------------------- Wikimedia Commons

def _clean_html(s):
    return html.unescape(re.sub(r"<[^>]+>", "", s or "")).strip()


def commons_candidates(query, must_tokens, limit=6):
    """Search Commons files; keep only freely-licensed images whose title contains every required token."""
    params = {"action": "query", "format": "json", "generator": "search", "gsrnamespace": 6, "gsrsearch": query,
              "gsrlimit": 20, "prop": "imageinfo", "iiprop": "url|extmetadata|size|mime", "iiurlwidth": 1200}
    try:
        pages = (_get("https://commons.wikimedia.org/w/api.php", params=params).json().get("query") or {}).get("pages") or {}
    except (requests.RequestException, ValueError):
        return []
    out = []
    for pg in sorted(pages.values(), key=lambda x: x.get("index", 99)):
        title = pg.get("title", "")
        low = re.sub(r"[_\-]", " ", title.lower())
        if not all(t.lower() in low.replace(" ", "") or t.lower() in low for t in must_tokens):
            continue
        ii = (pg.get("imageinfo") or [{}])[0]
        if ii.get("mime") not in ("image/jpeg", "image/png", "image/webp"):
            continue
        if min(ii.get("width", 0), ii.get("height", 0)) < 400:
            continue
        meta = ii.get("extmetadata") or {}
        lic = _clean_html((meta.get("LicenseShortName") or {}).get("value"))
        if not licence_ok(lic):
            continue  # skips non-free, fair-use and NC/ND licences
        author = _clean_html((meta.get("Artist") or {}).get("value")) or "Unknown author"
        out.append({
            "file": title, "thumb": ii.get("thumburl") or ii.get("url"), "page": ii.get("descriptionurl"),
            "credit": {"source": "commons", "text": f"Photo: {author[:80]}, {lic}, via Wikimedia Commons",
                       "link": ii.get("descriptionurl"), "license": lic,
                       "license_url": (meta.get("LicenseUrl") or {}).get("value", "")},
        })
        if len(out) >= limit:
            break
    time.sleep(0.5)  # be polite to the Wikimedia API
    return out


def commons_query_for(product):
    """Return (query, required_tokens) for products with a distinctive model name, else None."""
    from .seo_hubs import model_of
    n = product["name"]
    model, kind = model_of(product)
    if kind in ("laptop", "desktop") and model:
        core = re.sub(r"^(HP|Dell|Lenovo|ASUS|Asus)\s+", "", model)
        toks = [t for t in re.findall(r"[A-Za-z]*\d+[A-Za-z]*|[A-Za-z]{4,}", core) if t.lower() not in ("gaming", "laptop")]
        return (f"{product['brand']} {core}", toks[:3] or [core])
    m = re.search(r"\b(L\d{4}|G\d{4}|LQ-\d{3}|LX-\d{3}|MF\d{4}|LBP\d{3,4}\w?|M\d{3}w|C9\d{2}e?|C\d{3}e?|R\d{3}s?|"
                  r"TX\d{3}|F18|UF\d{3}|XP[- ]?\d{3}\w?|7580g)\b", n, re.I)
    if m and product["brand"] != "Generic":
        return (f"{product['brand']} {m.group(1)}", [m.group(1)])
    return None
