"""A small upload-to-Markdown API around MarkItDown: size limit, extension allow-list, stream conversion, a timeout, and no URL inputs."""
import asyncio, io, os
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, File, HTTPException, UploadFile
from markitdown import MarkItDown, StreamInfo

MAX_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", 10 * 1024 * 1024))
ALLOWED = {".docx", ".xlsx", ".pptx", ".pdf", ".csv", ".html", ".epub"}
TIMEOUT_SECONDS = float(os.getenv("CONVERT_TIMEOUT", 60))

app = FastAPI(title="markitdown-api")
md = MarkItDown(enable_plugins=False)          # one converter, plugins off
pool = ThreadPoolExecutor(max_workers=2)        # conversions are CPU-bound: keep this small

@app.post("/convert")
async def convert(file: UploadFile = File(...)):
    ext = os.path.splitext(file.filename or "")[1].lower()
    if ext not in ALLOWED:
        raise HTTPException(415, f"File type {ext or '(none)'} is not allowed")
    data = await file.read(MAX_BYTES + 1)       # never read more than the limit
    if len(data) > MAX_BYTES:
        raise HTTPException(413, f"File is larger than {MAX_BYTES} bytes")
    loop = asyncio.get_running_loop()
    job = loop.run_in_executor(pool, lambda: md.convert_stream(io.BytesIO(data), stream_info=StreamInfo(extension=ext)).markdown)
    try:
        text = await asyncio.wait_for(job, TIMEOUT_SECONDS)
    except asyncio.TimeoutError:
        raise HTTPException(504, "Conversion took too long")
    except Exception as e:                      # do not leak internals
        raise HTTPException(422, f"Could not convert this file ({type(e).__name__})")
    return {"filename": file.filename, "characters": len(text), "markdown": text}

@app.get("/health")
def health(): return {"ok": True}
