# [CRUCIBLE-SEED]
# category: command_injection
# severity: critical
# language: python
# expected: command injection via subprocess.Popen with shell=True and f-string

import subprocess
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class ImageRequest(BaseModel):
    image_path: str   # user-controlled
    width: int
    height: int
    quality: int = 85


class ReportRequest(BaseModel):
    format: str       # user-controlled
    date_range: str   # user-controlled


@app.post("/images/thumbnail")
def generate_thumbnail(req: ImageRequest):
    # image_path is user-controlled — injection via shell metacharacters
    cmd = f"ffmpeg -i {req.image_path} -vf scale={req.width}:{req.height} -q:v {req.quality} out.jpg"
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate(timeout=30)
    return {"output": out.decode(), "errors": err.decode()}


@app.post("/reports/generate")
def generate_report(req: ReportRequest):
    cmd = f"python3 scripts/report.py --format {req.format} --range {req.date_range}"
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out, _ = proc.communicate()
    return {"path": out.decode().strip()}
