import re, unicodedata
from datetime import datetime
from pathlib import Path
from uuid import uuid4
from PIL import Image
from flask import current_app
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}

def make_slug(value):
    value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii").lower()
    return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", value)).strip("-") or "konten"

def unique_slug(model, value, exclude_id=None):
    base, candidate, i = make_slug(value), make_slug(value), 2
    while True:
        query = model.query.filter_by(slug=candidate)
        if exclude_id is not None:
            query = query.filter(model.id != exclude_id)
        if query.first() is None:
            return candidate
        candidate, i = f"{base}-{i}", i + 1

def save_image(file_storage):
    if not file_storage or not file_storage.filename:
        return None
    suffix = Path(secure_filename(file_storage.filename)).suffix.lower()
    if suffix not in ALLOWED_EXTENSIONS:
        raise ValueError("Format gambar harus JPG, PNG, atau WEBP.")
    try:
        file_storage.stream.seek(0)
        image = Image.open(file_storage.stream)
        image.verify()
        file_storage.stream.seek(0)
        image = Image.open(file_storage.stream)
        image.thumbnail((2200, 2200))
        name = f"{uuid4().hex}{suffix}"
        folder = Path(current_app.config["UPLOAD_FOLDER"])
        folder.mkdir(parents=True, exist_ok=True)
        image.convert("RGB").save(folder / name, quality=88, optimize=True)
        return f"uploads/{name}"
    except Exception as exc:
        raise ValueError("File tersebut bukan gambar yang valid.") from exc
