"""Stateless public manifest preflight. Has no signing keys or effect adapters."""
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from .inspect import inspect_manifest
from .manifest_io import load_manifest_yaml_bytes, MAX_MANIFEST_BYTES
from .errors import ScopeWritError

app = FastAPI(title="ScopeWrit manifest preflight", docs_url=None, redoc_url=None, openapi_url=None)

@app.get('/api/health')
def health():
    return {'status':'ok','mode':'unsigned-manifest-inspection','authority_granted':False}

@app.post('/api/inspect')
async def inspect(request: Request):
    body=bytearray()
    async for chunk in request.stream():
        body.extend(chunk)
        if len(body)>MAX_MANIFEST_BYTES:
            return JSONResponse({'error':'Manifest exceeds 256 KiB.'},status_code=413)
    try:
        result=inspect_manifest(load_manifest_yaml_bytes(bytes(body)))
        return JSONResponse(result,headers={'Cache-Control':'no-store'})
    except (ScopeWritError,ValueError,TypeError,RecursionError) as exc:
        return JSONResponse({'error':str(exc)[:500]},status_code=400,headers={'Cache-Control':'no-store'})
