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}")
    async def ui_task_detail(task_id: str) -> HTMLResponse:
        safe_id = html.escape(task_id)
        body = f"""
<h1>Task: <code>{safe_id}</code></h1>
<div class="card">
  <div class="row">
    <a class="btn" href="/ui/tasks/{safe_id}/logs" style="display:inline-block">Logs</a>
    <button class="btn" id="refresh">Refresh</button>
    <button class="btn danger" id="cancel">Cancel</button>
    <a class="btn" href="/ui/tasks" style="display:inline-block">Back</a>
  </div>
  <div style="height:10px"></div>
  <pre id="out" class="muted">Loading...</pre>
</div>
<div style="height:12px"></div>
<div class="card">
  <h3 style="margin-top:0">W&amp;B</h3>
  <div class="muted">This is a best-effort hint. Run name maps to <code>ray_submission_id</code> (attempt).</div>
  <div style="height:10px"></div>
  <div class="row">
    <a class="btn" id="wandb-open" target="_blank" rel="noopener" href="#">Open W&amp;B (:8090)</a>
    <button class="btn" id="wandb-copy-run">Copy run</button>
  </div>
  <div style="height:10px"></div>
  <div class="muted">project: <code id="wandb-project">(unknown)</code></div>
  <div class="muted">run: <code id="wandb-run">(unknown)</code></div>
</div>
<div style="height:12px"></div>
<div class="card">
  <h3 style="margin-top:0">TaskSpec (YAML)</h3>
  <div class="muted">Resolved TaskSpec (includes default values; submission_id reflects latest attempt when available).</div>
  <div style="height:10px"></div>
  <pre id="spec" class="muted">Loading...</pre>
</div>
""".strip()
        script = f"""
document.getElementById("nav-ray-dashboard").href = curOriginWithPort(8265);
document.getElementById("wandb-open").href = curOriginWithPort(8090);
document.getElementById("wandb-copy-run").onclick = async () => {{ await copyText((document.getElementById("wandb-run").textContent || \"\").trim()); }};
const out = document.getElementById("out");
const spec = document.getElementById("spec");
async function refresh() {{
  out.textContent = "Loading...";
  spec.textContent = "Loading...";
  const resp = await apiFetch("/api/v2/tasks/{task_id}");
  const text = await resp.text();
  if (!resp.ok) {{ out.textContent = "Error: " + resp.status + "\\n" + text; return; }}
  const obj = JSON.parse(text);
  out.textContent = fmtJson(obj);
  const p = document.getElementById("wandb-project");
  const r = document.getElementById("wandb-run");
  const w = (obj.latest_attempt && obj.latest_attempt.wandb) ? obj.latest_attempt.wandb : null;
  if (w) {{
    p.textContent = w.project_name || "(unknown)";
    r.textContent = w.run_name || "(unknown)";
  }} else {{
    p.textContent = "(not available)";
    r.textContent = "(not available)";
  }}

  const resp2 = await apiFetch("/api/v2/tasks/{task_id}/spec");
  const text2 = await resp2.text();
  spec.textContent = resp2.ok ? text2 : ("Error: " + resp2.status + "\\n" + text2);
}}
document.getElementById("refresh").onclick = refresh;
document.getElementById("cancel").onclick = async () => {{
  if (!confirm("Cancel this task?")) return;
  const resp = await apiFetch("/api/v2/tasks/{task_id}:cancel", {{ method: "POST" }});
  const text = await resp.text();
  out.textContent = (resp.ok ? "Canceled.\\n" : "Error: " + resp.status + "\\n") + text;
  setTimeout(refresh, 800);
}};
refresh();
""".strip()
        return HTMLResponse(content=page(f"Task {task_id}", "tasks", body, script))

