from __future__ import annotations

import time
from typing import Any, Dict, List

from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI(title="aistalk-bridge-lite", version="0.1.0")

_MAX_EVENTS = 200
_events: List[Dict[str, Any]] = []


def _push(item: Dict[str, Any]) -> None:
    _events.append(item)
    if len(_events) > _MAX_EVENTS:
        del _events[: len(_events) - _MAX_EVENTS]


@app.get("/healthz")
async def healthz() -> Dict[str, Any]:
    return {"status": "ok", "service": "aistalk-bridge-lite", "events": len(_events)}


@app.get("/health")
async def health() -> Dict[str, Any]:
    return await healthz()


@app.get("/api/health")
async def api_health() -> Dict[str, Any]:
    return await healthz()


@app.post("/api/events")
@app.post("/events")
@app.post("/v1/events")
async def accept_events(payload: Dict[str, Any]) -> Dict[str, Any]:
    _push({"ts": time.time(), "kind": "event", "payload": payload})
    return {"ok": True, "accepted": "event"}


@app.post("/api/text")
@app.post("/text")
@app.post("/v1/text")
async def accept_text(payload: Dict[str, Any]) -> Dict[str, Any]:
    _push({"ts": time.time(), "kind": "text", "payload": payload})
    return {"ok": True, "accepted": "text"}


@app.post("/api/audio")
@app.post("/audio")
@app.post("/v1/audio")
async def accept_audio(
    audio: UploadFile = File(...),
    meta: str = Form(""),
) -> Dict[str, Any]:
    raw = await audio.read()
    _push(
        {
            "ts": time.time(),
            "kind": "audio",
            "bytes": len(raw),
            "mime": audio.content_type or "application/octet-stream",
            "meta": meta[:2000],
        }
    )
    return {"ok": True, "accepted": "audio", "bytes": len(raw)}


@app.get("/api/recent")
async def recent(limit: int = 20) -> Dict[str, Any]:
    n = max(1, min(int(limit), 100))
    return {"ok": True, "items": _events[-n:]}
