import os
import re
import uuid
from fastapi.responses import JSONResponse
from PIL import Image

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
UPLOADS_DIR = os.path.join(BASE_DIR, "uploads")
UPLOAD_PUBLIC_PREFIX = "/pod-api/uploads"


def response_error(message: str, status_code: int = 400):
    return JSONResponse(content={"error": True, "message": message}, status_code=status_code)


def response_success(data):
    return JSONResponse(content={"error": False, "data": data}, status_code=200)


def ensure_upload_dir(sub_dir: str):
    upload_base_dir = os.path.join(UPLOADS_DIR, sub_dir)
    os.makedirs(upload_base_dir, mode=0o775, exist_ok=True)
    return upload_base_dir


def convert_to_jpg_and_compress(file_path: str):
    try:
        img = Image.open(file_path)
    except IOError:
        return file_path

    w, h = img.size
    max_dim = 2000
    ratio = min(max_dim / w, max_dim / h, 1)

    if ratio < 1:
        nw, nh = int(w * ratio), int(h * ratio)
        img = img.resize((nw, nh), Image.Resampling.LANCZOS)

    if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
        bg = Image.new("RGB", img.size, (255, 255, 255))
        if img.mode == "RGBA":
            bg.paste(img, mask=img.split()[3])
        else:
            bg.paste(img)
        img = bg
    elif img.mode != "RGB":
        img = img.convert("RGB")

    base_name, _ = os.path.splitext(file_path)
    jpg_path = f"{base_name}.jpg"
    img.save(jpg_path, "JPEG", quality=80)

    if jpg_path != file_path and os.path.exists(file_path):
        os.remove(file_path)

    return jpg_path


def store_uploaded_file_content(
    filename: str,
    content: bytes,
    sub_dir: str,
    is_img: bool = False,
):
    upload_base_dir = ensure_upload_dir(sub_dir)

    original_name, ext = os.path.splitext(filename)
    safe_name = re.sub(r"[^a-z0-9\-]+", "-", original_name.lower()) or "file"
    rand_str = uuid.uuid4().hex[:12]
    ext = ext.strip(".") or "tmp"

    new_filename = f"{safe_name}-{rand_str}.{ext}"
    path = os.path.join(upload_base_dir, new_filename)

    with open(path, "wb") as f:
        f.write(content)

    if is_img:
        final_path = convert_to_jpg_and_compress(path)
        final_name = os.path.basename(final_path)
    else:
        final_name = new_filename

    return {
        "filename": final_name,
        "path": f"{UPLOAD_PUBLIC_PREFIX}/{sub_dir}/{final_name}",
    }