<script>
  import { onMount } from "svelte";
  import { api, formatTime } from "../lib/api.js";
  import Icon from "../lib/Icon.svelte";
  import StatusBadge from "../lib/StatusBadge.svelte";
  import Markdown from "../lib/Markdown.svelte";
  import ToolCallCard from "../lib/ToolCallCard.svelte";

  let tasks = $state([]);
  let loading = $state(true);
  let error = $state("");
  let tick = $state(0);

  let selected = $state(null);
  let detail = $state(null);
  let detailError = $state("");
  let detailTimer = null;

  const activeStatuses = ["queued", "running", "waiting_children"];

  function isActive(status) {
    return activeStatuses.includes(status);
  }

  async function loadTasks() {
    try {
      tasks = (await api("/api/tasks?limit=200")).tasks || [];
      error = "";
    } catch (caught) {
      error = caught.message;
    } finally {
      loading = false;
    }
  }

  function stopDetailPoll() {
    if (detailTimer) {
      clearInterval(detailTimer);
      detailTimer = null;
    }
  }

  async function loadDetail() {
    if (!selected) return;
    try {
      const [runRes, eventsRes] = await Promise.all([
        api(`/api/agent-runs/${encodeURIComponent(selected)}`),
        api(`/api/agent-runs/${encodeURIComponent(selected)}/events?limit=200`),
      ]);
      detail = {
        run: runRes.run,
        session_id: runRes.session_id,
        transcript: runRes.transcript || [],
        events: eventsRes.events || [],
      };
      detailError = "";
      if (!isActive(runRes.run.status)) stopDetailPoll();
    } catch (caught) {
      detailError = caught.message;
    }
  }

  function openDetail(run) {
    selected = run.id;
    detail = null;
    detailError = "";
    stopDetailPoll();
    loadDetail();
    detailTimer = setInterval(loadDetail, 2000);
  }

  function closeDetail() {
    selected = null;
    detail = null;
    detailError = "";
    stopDetailPoll();
  }

  function humanize(ms) {
    const secs = Math.floor(ms / 1000);
    if (secs < 60) return `${secs}s`;
    if (secs < 3600) return `${Math.floor(secs / 60)}m ${secs % 60}s`;
    return `${Math.floor(secs / 3600)}h ${Math.floor((secs % 3600) / 60)}m`;
  }

  function elapsed(ts) {
    void tick;
    if (!ts) return "";
    const ms = ts < 1e12 ? ts * 1000 : ts;
    const diff = Date.now() - ms;
    if (diff < 0) return "0s";
    return humanize(diff);
  }

  function durationBetween(start, end) {
    if (!start) return "";
    const a = start < 1e12 ? start * 1000 : start;
    const b = end ? (end < 1e12 ? end * 1000 : end) : Date.now();
    if (b < a) return "";
    return humanize(b - a);
  }

  function promptExcerpt(run) {
    return (run.prompt || run.task || "").slice(0, 120);
  }

  function toolResult(callId) {
    return (
      detail?.transcript.find(
        (message) => message.role === "tool" && message.tool_call_id === callId
      ) || null
    );
  }

  function signalSummary(event) {
    try {
      const payload = JSON.parse(event.payload_json);
      return payload.summary || payload.status || event.payload_json.slice(0, 200);
    } catch {
      return event.payload_json.slice(0, 200);
    }
  }

  onMount(() => {
    loadTasks();
    const listTimer = setInterval(loadTasks, 5000);
    const tickTimer = setInterval(() => (tick += 1), 1000);
    return () => {
      clearInterval(listTimer);
      clearInterval(tickTimer);
      stopDetailPoll();
    };
  });
</script>

<section class="page active content-page">
  {#if selected}
    <div class="detail-head">
      <button class="secondary" onclick={closeDetail}><Icon name="back" size={15} />返回</button>
      {#if detail}
        <div class="detail-title">
          <span class="mono">{detail.run.agent_id}</span>
          <StatusBadge status={detail.run.status} />
        </div>
      {/if}
    </div>

    {#if !detail && !detailError}
      <div class="loading">加载详情…</div>
    {:else if detailError}
      <div class="empty-card error-text">{detailError}</div>
    {:else if detail}
      <div class="detail-body">
        <article class="card">
          <div class="meta">
            <span>agent: <b>{detail.run.agent_id}</b></span>
            <span>provider: {detail.run.provider_name}</span>
            <span>model: {detail.run.model_id}</span>
            <span>mode: {detail.run.mode}</span>
            <span>depth: {detail.run.depth}</span>
            <span>{detail.run.tool_calls_count} 次工具调用 · {detail.run.iterations} 轮</span>
            {#if detail.session_id}<span>session: <span class="mono">{detail.session_id}</span></span>{/if}
            {#if detail.run.parent_run_id}<span>parent: <span class="mono">{detail.run.parent_run_id}</span></span>{/if}
            <span>开始 {formatTime(detail.run.started_at)}</span>
            <span>结束 {formatTime(detail.run.finished_at)}</span>
            <span>耗时 {durationBetween(detail.run.started_at, detail.run.finished_at)}</span>
          </div>
        </article>

        {#if detail.events.length}
          <div class="agent-event-cards" aria-label="运行事件">
            {#each detail.events as event (event.id)}
              <article class:warning={event.severity === "warning"} class:critical={event.severity === "critical"} class="agent-event-card">
                <span class="agent-event-icon"><Icon name="bot" size={14} /></span>
                <div class="agent-event-body">
                  <div class="agent-event-title">
                    {event.event_type === "signal" ? `信号 · ${event.severity || "info"}` : `完成 · ${event.status}`}
                    <span class="agent-event-delivery">{event.delivery === "steer" ? "steer" : "queue"}</span>
                  </div>
                  {#if event.event_type === "signal"}
                    {#if event.payload_json}<p>{signalSummary(event)}</p>{/if}
                  {:else}
                    <p class="agent-event-status">{event.status}{event.last_error ? ` · ${event.last_error}` : ""}</p>
                  {/if}
                </div>
              </article>
            {/each}
          </div>
        {/if}

        <div class="transcript">
          {#if detail.run.task}
            <div class="message user">
              <div class="avatar">任务</div>
              <div class="message-content">
                <div class="bubble"><Markdown content={detail.run.task} /></div>
              </div>
            </div>
          {/if}

          {#each detail.transcript.filter((m) => m.role !== "tool") as message (message.id)}
            <div class:assistant={message.role === "assistant"} class="message">
              <div class="avatar">{message.role === "assistant" ? "" : message.role}</div>
              <div class="message-content">
                {#if message.reasoning_content}
                  <details class="reasoning-block historical">
                    <summary>思考过程</summary>
                    <div class="reasoning-content"><Markdown content={message.reasoning_content} /></div>
                  </details>
                {/if}
                {#if message.content}<div class="bubble"><Markdown content={message.content} /></div>{/if}
                {#if message.tool_calls?.length}
                  <div class="tool-calls">
                    {#each message.tool_calls as call (call.id)}
                      <ToolCallCard {call} result={toolResult(call.id)} />
                    {/each}
                  </div>
                {/if}
              </div>
            </div>
          {/each}

          {#if detail.transcript.length === 0 && !detail.run.task}
            <div class="empty-card">无转录</div>
          {/if}
        </div>

        {#if detail.run.error}
          <article class="card error-text">{detail.run.error}</article>
        {/if}
      </div>
    {/if}
  {:else}
    <div class="toolbar">
      <div>
        <h2 style="margin:0">子代理活动</h2>
        <p style="margin:2px 0 0;color:var(--muted);font-size:12px">
          查看活动中的子代理与历史运行；子代理定义在「配置 → 子代理」中管理。
        </p>
      </div>
      <button class="secondary" onclick={loadTasks}><Icon name="refresh" size={16} />刷新</button>
    </div>

    {#if loading}
      <div class="loading">加载中…</div>
    {:else if error}
      <div class="empty-card error-text">{error}</div>
    {:else}
      {#if tasks.some((t) => isActive(t.status))}
        <h3 class="section-label">活动中</h3>
        <div class="cards">
          {#each tasks.filter((t) => isActive(t.status)) as task (task.id)}
            <article class="card">
              <div class="card-row">
                <div class="task-main">
                  <div class="run-row">
                    <span class="pulse"></span>
                    <span class="agent-tag">{task.agent_id || "general"}</span>
                    <span class="run-prompt">{promptExcerpt(task)}</span>
                    <StatusBadge status={task.status} />
                  </div>
                  <div class="meta">
                    <span>mode: {task.mode}</span>
                    <span>depth: {task.depth}</span>
                    <span class="elapsed">已运行 {elapsed(task.started_at || task.created_at)}</span>
                  </div>
                </div>
                <div class="card-actions">
                  <button class="secondary" onclick={() => openDetail(task)}><Icon name="more" size={15} />详情</button>
                </div>
              </div>
            </article>
          {/each}
        </div>
      {/if}

      <h3 class="section-label">历史活动</h3>
      <div class="cards">
        {#each tasks.filter((t) => !isActive(t.status)) as task (task.id)}
          <article class="card">
            <div class="card-row">
              <div class="task-main">
                <div class="run-row">
                  <span class="agent-tag">{task.agent_id || "general"}</span>
                  <span class="run-prompt">{promptExcerpt(task)}</span>
                  <StatusBadge status={task.status} />
                </div>
                <div class="meta">
                  <span>{formatTime(task.created_at)}</span>
                  <span>{task.tool_calls_count} 次工具调用 · {task.iterations} 轮</span>
                  {#if task.started_at && task.finished_at}<span>耗时 {durationBetween(task.started_at, task.finished_at)}</span>{/if}
                </div>
              </div>
              <div class="card-actions">
                <button class="secondary" onclick={() => openDetail(task)}><Icon name="more" size={15} />详情</button>
              </div>
            </div>
          </article>
        {:else}
          <div class="empty-card">暂无历史活动</div>
        {/each}
      </div>
    {/if}
  {/if}
</section>

<style>
  .detail-head { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
  .detail-title { display: flex; align-items: center; gap: 10px; }
  .detail-title .mono { font-size: 13px; color: var(--text-soft); }
  .detail-body { display: grid; gap: 12px; }
  .transcript { display: grid; gap: 4px; }
  .transcript .avatar { width: 28px; height: 28px; font-size: 10px; }
  .section-label { margin: 18px 0 8px; font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
  .task-main { flex: 1; min-width: 0; }
  .run-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  .agent-tag { font-size: 11px; color: var(--accent); background: var(--code-bg); border: 1px solid var(--line); border-radius: 4px; padding: 0 6px; font-family: var(--font-mono); }
  .run-prompt { flex: 1 1 200px; min-width: 120px; }
  .elapsed { color: var(--info); font-family: var(--font-mono); font-size: 11px; font-variant-numeric: tabular-nums; }
  .card-actions { display: flex; align-items: center; gap: 8px; }
  .mono { font-family: var(--font-mono); }
</style>
