from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import FileResponse
import httpx
import os

UPSTREAM = "http://127.0.0.1:3007/ingest_signed"
app = FastAPI(title="Health Bridge public ingest proxy")

@app.get('/health')
async def health():
    return {'status':'ok'}

@app.get('/fba/{filename}')
async def serve_fba(filename: str):
    fba_path = f'/home/ubuntu/baby-checklist/public/{filename}'
    if not os.path.exists(fba_path):
        raise HTTPException(status_code=404, detail='not found')
    return FileResponse(fba_path, media_type='application/octet-stream', filename=filename)

@app.get('/static/{filepath:path}')
async def serve_static(filepath: str):
    full = f'/home/ubuntu/baby-checklist/public/{filepath}'
    if not os.path.exists(full):
        raise HTTPException(status_code=404, detail='not found')
    import mimetypes
    mime, _ = mimetypes.guess_type(full)
    return FileResponse(full, media_type=mime or 'application/octet-stream')

@app.api_route('/{path:path}', methods=['GET','PUT','PATCH','DELETE','OPTIONS','HEAD'])
async def deny(path: str):
    raise HTTPException(status_code=404, detail='not found')

@app.post('/ingest_signed')
async def ingest_signed(request: Request):
    body = await request.body()
    headers = {
        k: v for k, v in request.headers.items()
        if k.lower() in {'content-type', 'x-hb-device', 'x-hb-timestamp', 'x-hb-nonce', 'x-hb-signature'}
    }
    async with httpx.AsyncClient(timeout=20.0) as client:
        resp = await client.post(UPSTREAM, content=body, headers=headers)
    return resp.json()

# Tailscale Funnel strips the matched /ingest_signed prefix when forwarding
# to this proxy (so the request arrives at POST / with the original body+headers).
# Accept POST / as a fallback so signed ingests still work.
@app.post('/')
async def ingest_root_fallback(request: Request):
    return await ingest_signed(request)
