import os
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

app = FastAPI(title="VTU Python Sidecar", version="0.1.0")
INTERNAL_TOKEN = os.getenv("VTU_INTERNAL_TOKEN", "")

def require_token(authorization: str | None) -> None:
    if not INTERNAL_TOKEN:
        raise HTTPException(status_code=503, detail="Internal token is not configured")
    expected = f"Bearer {INTERNAL_TOKEN}"
    if authorization != expected:
        raise HTTPException(status_code=401, detail="Unauthorized")

class LatencySample(BaseModel):
    provider: str
    latency_ms: int
    success: bool

@app.get("/health")
def health():
    return {"ok": True, "service": "vtu-python"}

@app.post("/internal/telemetry/provider")
def provider_telemetry(
    sample: LatencySample,
    authorization: str | None = Header(default=None),
):
    require_token(authorization)
    # Phase 1 placeholder. Later: aggregate provider reliability metrics.
    return {"accepted": True, "provider": sample.provider}
