"""Image/video processing: originals are kept; the site serves web + thumb copies."""
import os
import re
import shutil
import subprocess
import uuid

from PIL import Image, ImageOps

IMAGE_EXT = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tif", ".tiff"}
VIDEO_EXT = {".mp4", ".mov", ".m4v", ".webm"}
WEB_MAX = 1920
THUMB_MAX = 640
DUP_DISTANCE = 10  # dHash bits (of 256) – below this two photos are "the same shot"

try:  # optional iPhone HEIC support
    from pillow_heif import register_heif_opener  # type: ignore
    register_heif_opener()
    IMAGE_EXT |= {".heic", ".heif"}
except Exception:
    pass


def safe_name(name):
    base, ext = os.path.splitext(os.path.basename(name or "file"))
    base = re.sub(r"[^A-Za-z0-9]+", "-", base).strip("-").lower()[:40] or "file"
    return f"{base}-{uuid.uuid4().hex[:8]}", ext.lower()


def kind_of(filename):
    ext = os.path.splitext(filename or "")[1].lower()
    if ext in IMAGE_EXT:
        return "image"
    if ext in VIDEO_EXT:
        return "video"
    return None


def _ensure(*parts):
    p = os.path.join(*parts)
    os.makedirs(p, exist_ok=True)
    return p


def dhash(img):
    g = img.convert("L").resize((17, 16), Image.LANCZOS)
    px = g.load()
    bits = 0
    i = 0
    for y in range(16):
        for x in range(16):
            if px[x, y] > px[x + 1, y]:
                bits |= 1 << i
            i += 1
    return format(bits, "064x")


def hamming(a, b):
    try:
        return bin(int(a, 16) ^ int(b, 16)).count("1")
    except (TypeError, ValueError):
        return 999


def is_duplicate(phash, existing_hashes):
    return any(hamming(phash, h) <= DUP_DISTANCE for h in existing_hashes if h)


def open_image(src):
    """Open + verify an image; raises on truncated/corrupt files."""
    with Image.open(src) as probe:
        probe.verify()
    if hasattr(src, "seek"):
        src.seek(0)
    img = Image.open(src)
    img.load()
    return ImageOps.exif_transpose(img)


def _save_jpeg(img, path, max_side, quality):
    im = img.copy()
    im.thumbnail((max_side, max_side), Image.LANCZOS)
    if im.mode in ("RGBA", "LA", "P"):
        bg = Image.new("RGB", im.size, "white")
        im = im.convert("RGBA")
        bg.paste(im, mask=im.split()[-1])
        im = bg
    else:
        im = im.convert("RGB")
    im.save(path, "JPEG", quality=quality, optimize=True, progressive=True)
    return im.size


def process_image(src, uploads_root, subdir, filename=None, keep_original=True,
                  web_max=WEB_MAX, thumb_max=THUMB_MAX, img=None):
    """src: path or file-like. Returns dict of relative paths + metadata."""
    filename = filename or (src if isinstance(src, str) else "image.jpg")
    stem, ext = safe_name(filename)
    img = img or open_image(src)
    out = {"kind": "image"}
    if keep_original:
        odir = _ensure(uploads_root, subdir, "original")
        opath = os.path.join(odir, stem + (ext or ".jpg"))
        if isinstance(src, str):
            shutil.copyfile(src, opath)
        else:
            src.seek(0)
            with open(opath, "wb") as fh:
                shutil.copyfileobj(src, fh)
        out["original"] = os.path.relpath(opath, uploads_root)
    wdir = _ensure(uploads_root, subdir, "web")
    tdir = _ensure(uploads_root, subdir, "thumb")
    wpath = os.path.join(wdir, stem + ".jpg")
    tpath = os.path.join(tdir, stem + ".jpg")
    w, h = _save_jpeg(img, wpath, web_max, 84)
    _save_jpeg(img, tpath, thumb_max, 78)
    out.update(web=os.path.relpath(wpath, uploads_root),
               thumb=os.path.relpath(tpath, uploads_root),
               width=w, height=h, phash=dhash(img))
    return out


def process_video(src, uploads_root, subdir, filename=None):
    filename = filename or (src if isinstance(src, str) else "video.mp4")
    stem, ext = safe_name(filename)
    vdir = _ensure(uploads_root, subdir, "video")
    vpath = os.path.join(vdir, stem + (ext or ".mp4"))
    if isinstance(src, str):
        shutil.copyfile(src, vpath)
    else:
        src.seek(0)
        with open(vpath, "wb") as fh:
            shutil.copyfileobj(src, fh)
    out = {"kind": "video", "original": os.path.relpath(vpath, uploads_root),
           "web": os.path.relpath(vpath, uploads_root), "thumb": "", "width": 0,
           "height": 0, "phash": ""}
    ff = shutil.which("ffmpeg")
    if ff:
        tdir = _ensure(uploads_root, subdir, "thumb")
        tpath = os.path.join(tdir, stem + "-poster.jpg")
        try:
            subprocess.run([ff, "-y", "-loglevel", "error", "-ss", "1", "-i", vpath,
                            "-frames:v", "1", "-vf", f"scale='min({THUMB_MAX},iw)':-2", tpath],
                           check=True, timeout=60)
            out["thumb"] = os.path.relpath(tpath, uploads_root)
        except Exception:
            pass
    return out


def delete_files(uploads_root, *rel_paths):
    for rel in rel_paths:
        if not rel:
            continue
        p = os.path.normpath(os.path.join(uploads_root, rel))
        if p.startswith(os.path.normpath(uploads_root)) and os.path.isfile(p):
            try:
                os.remove(p)
            except OSError:
                pass
