"""Fetch free, legal product images. Run on a machine with normal internet access (your laptop or server).

Official manufacturer photos (Open Icecat), attached directly because matches are exact:
    python manage.py fetch_images --icecat-user YOUR_ICECAT_USERNAME [--app-key KEY] [--csv image-sources.csv]

Free-licence photos (Wikimedia Commons), saved for review first:
    python manage.py fetch_images --commons --review-dir commons-review
    # open the folder, DELETE any photo that is not the exact model, then:
    python manage.py import_photos commons-review --manifest commons-review/manifest.json

Add --limit N to try a few products first, --dry-run to see what would happen.
"""
import csv
import io
import json
import os

from django.core.management.base import BaseCommand, CommandError

from store.db import get_db
import re

from store.image_sources import commons_candidates, commons_query_for, download, icecat_images
from store.images import process
from store.utils import now


class Command(BaseCommand):
    help = "Fetch product photos from Open Icecat (official) and/or Wikimedia Commons (free licences)"

    def add_arguments(self, parser):
        parser.add_argument("--icecat-user")
        parser.add_argument("--app-key")
        parser.add_argument("--csv", help="CSV from export_image_sources with mpn/gtin filled in")
        parser.add_argument("--commons", action="store_true")
        parser.add_argument("--review-dir", default="commons-review")
        parser.add_argument("--limit", type=int, default=0)
        parser.add_argument("--max-images", type=int, default=4)
        parser.add_argument("--include-with-photos", action="store_true", help="Also process products that already have photos")
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, **o):
        if not o["icecat_user"] and not o["commons"]:
            raise CommandError("Choose a source: --icecat-user USERNAME and/or --commons")
        db = get_db()
        if o["csv"]:
            self._load_codes(db, o["csv"])
        q = {"active": True}
        if not o["include_with_photos"]:
            q["$or"] = [{"images": {"$size": 0}}, {"images": {"$exists": False}}]
        products = list(db.products.find(q))
        if o["limit"]:
            products = products[: o["limit"]]

        if o["icecat_user"]:
            self._icecat(db, products, o)
            if not o["include_with_photos"]:  # don't search Commons for products Icecat just filled
                products = [p for p in products if not (db.products.find_one({"_id": p["_id"]}) or {}).get("images")]
        if o["commons"]:
            self._commons(products, o)

    # ------------------------------------------------------------------
    def _load_codes(self, db, path):
        n = 0
        with open(path, encoding="utf-8-sig") as f:
            for row in csv.DictReader(f):
                upd = {}
                if (row.get("mpn") or "").strip():
                    upd["mpn"] = row["mpn"].strip().upper()
                if (row.get("gtin") or "").strip():
                    upd["gtin"] = "".join(ch for ch in row["gtin"] if ch.isdigit())
                if upd:
                    n += db.products.update_one({"slug": row["slug"]}, {"$set": upd}).modified_count
        self.stdout.write(f"Saved part numbers/barcodes for {n} products from {path}")

    def _icecat(self, db, products, o):
        found = missing = 0
        candidates = [p for p in products if p.get("gtin") or p.get("mpn")]
        if not candidates:
            self.stdout.write("Icecat: no products have an MPN or GTIN yet. Run export_image_sources, fill the codes, "
                              "and pass --csv.")
            return
        for p in candidates:
            res = icecat_images(o["icecat_user"], brand=p.get("brand"), mpn=p.get("mpn"), gtin=p.get("gtin"),
                                app_key=o["app_key"], limit=o["max_images"])
            if not res:
                missing += 1
                self.stdout.write(f"  Icecat: not found  {p['slug']}  ({p.get('mpn') or p.get('gtin')})")
                continue
            if not self._title_matches(p, res["title"]):
                missing += 1
                self.stdout.write(self.style.WARNING(
                    f"  Icecat: SKIPPED {p['slug']}: Icecat returned \"{res['title']}\", which doesn't match this "
                    f"product's model. Check the part number."))
                continue
            if o["dry_run"]:
                self.stdout.write(f"  Icecat: would add {len(res['images'])} image(s) to {p['slug']}  [{res['title']}]")
                found += 1
                continue
            urls, credits = [], []
            for u in res["images"]:
                try:
                    out = process(io.BytesIO(download(u)), os.path.basename(u), hint=p["slug"])
                except Exception as e:  # noqa: BLE001
                    self.stderr.write(f"    skip image {u}: {e}")
                    continue
                urls.append(out["url"])
                credits.append({**res["credit"], "url": out["url"]})
            if urls:
                db.products.update_one({"_id": p["_id"]}, {"$push": {"images": {"$each": urls},
                                                                     "image_credits": {"$each": credits}},
                                                           "$set": {"updated_at": now()}})
                found += 1
                self.stdout.write(f"  Icecat: {len(urls)} image(s) → {p['slug']}")
        self.stdout.write(self.style.SUCCESS(f"Icecat done: {found} products updated, {missing} not in Open Icecat."))

    @staticmethod
    def _title_matches(p, title):
        """Safety check so a wrong part number can never attach another product's photos.

        The Icecat title must contain the product's model tokens (e.g. '840' and 'G5'). For products without a
        recognised model, every number-bearing token in the name (e.g. '840', 'G3', '2280', '16GB') must appear,
        or, if the name has none, at least two of its significant words must.
        """
        if not title:
            return False
        t = re.sub(r"[\s\-_]", "", title.lower())
        qt = commons_query_for(p)
        if qt:
            return all(re.sub(r"[\s\-_]", "", tok.lower()) in t for tok in qt[1])
        name = re.sub(r"\(.*?\)", " ", p["name"])
        numeric = [w for w in re.findall(r"[A-Za-z]*\d+[A-Za-z]*", name) if len(w) >= 2][:4]
        if numeric:
            return all(w.lower() in t for w in numeric)
        stop = {"with", "for", "and", "the", "new", "original", "refurbished", "kenya"}
        words = [w.lower() for w in re.findall(r"[A-Za-z]{4,}", name) if w.lower() not in stop]
        return sum(1 for w in set(words) if w in title.lower()) >= min(2, len(set(words)))

    def _commons(self, products, o):
        folder = o["review_dir"]
        os.makedirs(folder, exist_ok=True)
        manifest_path = os.path.join(folder, "manifest.json")
        manifest = json.load(open(manifest_path)) if os.path.exists(manifest_path) else {}
        searched = saved = 0
        cache = {}
        for p in products:
            qt = commons_query_for(p)
            if not qt:
                continue
            searched += 1
            key = qt[0].lower()
            if key not in cache:
                cache[key] = commons_candidates(qt[0], qt[1], limit=3)
            for i, c in enumerate(cache[key][: o["max_images"]], start=1):
                fname = f"{p['slug']}{'' if i == 1 else f'-{i}'}.jpg"
                if o["dry_run"]:
                    self.stdout.write(f"  Commons: {fname}  ←  {c['file']}  ({c['credit']['license']})")
                    continue
                try:
                    data = download(c["thumb"])
                except Exception as e:  # noqa: BLE001
                    self.stderr.write(f"    skip {c['file']}: {e}")
                    continue
                with open(os.path.join(folder, fname), "wb") as f:
                    f.write(data)
                manifest[fname] = {"slug": p["slug"], "credit": c["credit"], "source_file": c["file"]}
                saved += 1
        if not o["dry_run"]:
            with open(manifest_path, "w") as f:
                json.dump(manifest, f, indent=1)
            self._review_page(folder, manifest)
        self.stdout.write(self.style.SUCCESS(
            f"Commons: searched {searched} distinctive models, saved {saved} candidate photo(s) to {folder}/.\n"
            f"Open {folder}/review.html, DELETE every file that is not exactly the right model, then run:\n"
            f"  python manage.py import_photos {folder} --manifest {manifest_path}"))

    def _review_page(self, folder, manifest):
        rows = "".join(
            f"<figure><img src='{fn}' loading='lazy'><figcaption><b>{v['slug']}</b><br>{fn}<br>"
            f"<small>{v['credit']['text']}</small></figcaption></figure>"
            for fn, v in sorted(manifest.items()) if os.path.exists(os.path.join(folder, fn)))
        with open(os.path.join(folder, "review.html"), "w") as f:
            f.write("<!doctype html><meta charset=utf-8><title>Review Commons photos</title><style>body{font:14px sans-serif;"
                    "margin:20px}main{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px}"
                    "img{width:100%;height:190px;object-fit:contain;background:#f3f3f3}figure{margin:0;border:1px solid #ddd;"
                    "padding:8px}</style><h1>Check each photo is the exact model</h1><p>Delete wrong files from the folder, "
                    f"then import.</p><main>{rows}</main>")
