from __future__ import annotations

import hashlib

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, PlainTextResponse, Response

from sitedrop.server.storage import InvalidNameError

router = APIRouter()


@router.get("/{name:path}")
def serve_site(name: str, request: Request):
    storage = request.app.state.storage
    try:
        content = storage.get(name)
    except InvalidNameError:
        return PlainTextResponse("Not found", status_code=404)
    if content is None:
        return PlainTextResponse("Not found", status_code=404)

    etag = f'"{hashlib.sha256(content.encode()).hexdigest()}"'
    if request.headers.get("if-none-match") == etag:
        return Response(status_code=304, headers={"ETag": etag})
    return HTMLResponse(content, headers={"ETag": etag, "Cache-Control": "no-cache"})
