import asyncio
from pathlib import Path

from fastapi import FastAPI, WebSocket
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

from opengit.agents.core import run_heartbeat

app = FastAPI(title="OpenGit SRE Dashboard")

STATIC_DIR = Path(__file__).parent / "static"
STATIC_DIR.mkdir(exist_ok=True)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")


@app.get("/")
def read_root():
    return FileResponse(STATIC_DIR / "index.html")


@app.websocket("/ws/logs")
async def websocket_logs(websocket: WebSocket):
    await websocket.accept()

    async def sender(payload):
        await websocket.send_json(payload)

    def emit(payload):
        asyncio.create_task(sender(payload))

    try:
        await run_heartbeat(demo=False, emit=emit)
    except Exception as e:
        await websocket.send_json({"agent": "system", "msg": f"ERROR: {e}"})
    await asyncio.sleep(0.5)
    await websocket.close()


@app.post("/api/heartbeat")
async def trigger_heartbeat():
    """Cloud Scheduler / Webhook trigger for the OpenGit heartbeat."""
    asyncio.create_task(run_heartbeat(demo=False))
    return {"status": "triggered", "message": "OpenGit SRE Heartbeat initiated via Webhook."}
