
from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import JSONResponse
from tempfile import NamedTemporaryFile
from pathlib import Path
from klt414.importers import read_any_document
from klt414.engine import score_text, extract_metadata

app = FastAPI(title='KLT 4.14 API')

@app.post('/api/analyze')
async def analyze(file: UploadFile = File(...), ideal: str = Form(''), lang: str = Form('ru')):
    suffix = Path(file.filename).suffix
    with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
        tmp.write(await file.read())
        tmp_path = tmp.name
    info = read_any_document(tmp_path, lang=lang)
    meta = extract_metadata(info['text'], file.filename)
    result = score_text(info['text'], ideal, lang=lang)
    return JSONResponse({'metadata': meta, 'import': info, 'result': result})
