"""
Standalone production server — Python 3.9 compatible, no package dependencies.
"""
import json
import os
from pathlib import Path

from fastapi import FastAPI, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.gzip import GZipMiddleware

# Paths relative to this file
_BASE     = Path(__file__).resolve().parent
_WEB_DIR  = _BASE / "src" / "web"
_DATA_DIR = _BASE / "data"
_NET_FILE = _BASE / "data" / "processed" / "network_index.json"

app = FastAPI()
_network_index = None  # None = not loaded yet


class CacheMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        path = request.url.path
        qs   = request.url.query
        if path == "/" or path.endswith(".html"):
            response.headers["Cache-Control"] = "no-cache"
        elif path.endswith(".js") and qs:
            response.headers["Cache-Control"] = "public, max-age=86400, immutable"
        elif path.startswith("/data/processed/") and path.endswith(".json"):
            response.headers["Cache-Control"] = "public, max-age=3600"
        return response


app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(CacheMiddleware)


def _get_network_index():
    global _network_index
    if _network_index is None:
        if _NET_FILE.exists():
            with open(_NET_FILE) as f:
                _network_index = json.load(f)
        else:
            _network_index = {}
    return _network_index


@app.get("/api/network")
async def get_network(request: Request):
    smiles = request.query_params.get("smiles", "")
    data = _get_network_index().get(smiles)
    if data is None:
        raise HTTPException(status_code=404, detail="not found")
    return data


app.mount("/data", StaticFiles(directory=str(_DATA_DIR)), name="data")
app.mount("/", StaticFiles(directory=str(_WEB_DIR), html=True), name="web")
