# [CRUCIBLE-SEED]
# category: deserialization
# severity: critical
# language: python
# expected: pickle.load used with untrusted file upload and shelve with user-controlled key

import pickle
import shelve
from fastapi import FastAPI, UploadFile, File, HTTPException

app = FastAPI()


@app.post("/models/load")
async def load_model(file: UploadFile = File(...)):
    contents = await file.read()
    try:
        # User-uploaded .pkl file deserialized without any validation
        model = pickle.loads(contents)
        return {"model_type": type(model).__name__}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/cache/{key}")
def get_from_cache(key: str):
    # shelve uses pickle internally — user-controlled key reads arbitrary shelf entries
    with shelve.open("/var/cache/app_cache") as db:
        if key not in db:
            raise HTTPException(status_code=404, detail="Not found")
        value = db[key]  # deserialized via pickle
    return {"value": value}


@app.post("/tasks/restore")
async def restore_task_state(file: UploadFile = File(...)):
    data = await file.read()
    state = pickle.loads(data)  # untrusted task state from client
    return {"task_id": state.get("id"), "status": state.get("status")}
