from __future__ import annotations

import html

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

from ..layout.page import page


def register(app: FastAPI) -> None:
    @app.get("/ui/tasks/{task_id}/logs")
    async def ui_task_logs(task_id: str) -> HTMLResponse:
        safe_id = html.escape(task_id)
        body = f"""
<h1>Logs: <code>{safe_id}</code></h1>
<div class="card">
  <div class="row">
    <button class="btn" id="refresh">Refresh</button>
    <label class="muted">Auto refresh <input type="checkbox" id="auto" /></label>
    <a class="btn" href="/ui/tasks/{safe_id}" style="display:inline-block">Back</a>
  </div>
  <div style="height:10px"></div>
  <pre id="out" class="muted">Loading...</pre>
</div>
""".strip()
        script = f"""
document.getElementById("nav-ray-dashboard").href = curOriginWithPort(8265);
const out = document.getElementById("out");
let timer = null;
async function refresh() {{
  const resp = await apiFetch("/api/v2/tasks/{task_id}/logs?tail=4000");
  const text = await resp.text();
  out.textContent = resp.ok ? text : ("Error: " + resp.status + "\\n" + text);
}}
document.getElementById("refresh").onclick = refresh;
document.getElementById("auto").onchange = (e) => {{
  if (e.target.checked) {{
    timer = setInterval(refresh, 2000);
  }} else {{
    if (timer) clearInterval(timer);
    timer = null;
  }}
}};
refresh();
""".strip()
        return HTMLResponse(content=page(f"Logs {task_id}", "tasks", body, script))

