import os
import shutil
import uuid
from fastapi import UploadFile, File, HTTPException
from .core import STORE_DIR

FILES: dict[str, str] = {}  # file_id -> abs path

ALLOWED_EXTS = {".mat", ".h5", ".hdf5", ".json"}

def save_upload(file: UploadFile = File(...)) -> dict:
    ext = (os.path.splitext(file.filename or "")[1] or "").lower()
    if ext not in ALLOWED_EXTS:
        raise HTTPException(400, f"Поддерживаются: {', '.join(sorted(ALLOWED_EXTS))}")
    file_id = str(uuid.uuid4())
    save_path = os.path.join(STORE_DIR, f"{file_id}_{file.filename}")
    with open(save_path, "wb") as f:
        shutil.copyfileobj(file.file, f)
    FILES[file_id] = save_path
    return {"file_id": file_id, "filename": file.filename}
