<template>
  <transition name="overlay-fade">
    <div v-if="activeAgent" class="subagent-activity-overlay" @click.self="close">
      <div class="subagent-activity-modal">
        <div class="subagent-activity-header">
          <div class="subagent-activity-title">
            子智能体 #{{ activeAgent.agent_id || activeAgent.task_id }} 进度
          </div>
          <button type="button" class="subagent-activity-close" @click="close">×</button>
        </div>
        <div class="subagent-activity-meta">
          <span class="subagent-activity-status" :class="activeAgent.status || ''">{{
            activeAgent.status || 'running'
          }}</span>
          <span class="subagent-activity-summary" v-if="activeAgent.summary">{{
            activeAgent.summary
          }}</span>
        </div>
        <div class="subagent-activity-actions" v-if="canStop">
          <button
            type="button"
            class="subagent-stop-btn"
            :disabled="stopLoading"
            @click="handleStop"
          >
            {{ stopLoading ? '停止中...' : '手动停止' }}
          </button>
          <span v-if="stopError" class="subagent-activity-error">{{ stopError }}</span>
        </div>
        <div class="subagent-activity-body">
          <div v-if="activityError" class="subagent-activity-error">{{ activityError }}</div>
          <div v-else-if="!displayItems.length" class="subagent-activity-empty">
            {{ activityLoading ? '正在读取子智能体活动...' : '暂无活动记录' }}
          </div>
          <div v-else class="subagent-activity-list">
            <div v-for="item in displayItems" :key="item.key" class="subagent-activity-item">
              <span class="subagent-activity-text">{{ item.text }}</span>
              <span class="subagent-activity-state" :class="item.state">{{ item.stateLabel }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useSubAgentStore } from '@/stores/subAgent';

type ActivityEntry = {
  id?: string;
  tool?: string;
  status?: string;
  args?: Record<string, any>;
  ts?: number;
};

const subAgentStore = useSubAgentStore();
const { activeAgent, activityEntries, activityLoading, activityError, stoppingTaskIds } =
  storeToRefs(subAgentStore);
const stopError = ref('');

const close = () => {
  subAgentStore.closeSubAgent();
};

const normalizeStatus = (status?: string) => {
  if (status === 'running' || status === 'in_progress') return 'running';
  if (status === 'completed' || status === 'done' || status === 'success') return 'completed';
  if (status === 'failed' || status === 'error') return 'failed';
  return status || 'running';
};

const buildText = (entry: ActivityEntry) => {
  const tool = entry.tool || '';
  const args = entry.args || {};
  if (tool === 'read_file') {
    const path = args.path || args.file_path || '';
    return `阅读 ${path}`;
  }
  if (tool === 'read_skill') {
    const skillName = args.skill_name || '';
    return `阅读技能 ${skillName}`;
  }
  if (tool === 'search_workspace') {
    const query = args.query || args.keyword || '';
    return `在工作区搜索 ${query}`;
  }
  if (tool === 'web_search') {
    const query = args.query || args.q || '';
    return `在互联网中搜索 ${query}`;
  }
  if (tool === 'extract_webpage') {
    const url = args.url || '';
    return `在互联网中提取 ${url}`;
  }
  if (tool === 'run_command') {
    const command = args.command || '';
    return `运行命令 ${command}`;
  }
  if (tool === 'edit_file') {
    const path = args.path || args.file_path || '';
    return `编辑 ${path}`;
  }
  if (tool === 'read_mediafile') {
    const path = args.path || args.file_path || '';
    return `读取媒体文件 ${path}`;
  }
  return `${tool || '工具'}`;
};

const isTerminalStatus = (status?: string) => {
  const normalized = (status || '').toString().toLowerCase();
  return ['completed', 'failed', 'timeout', 'terminated', 'cancelled'].includes(normalized);
};

const canStop = computed(() => {
  if (!activeAgent.value?.task_id) return false;
  return !isTerminalStatus(activeAgent.value.status);
});

const stopLoading = computed(() => {
  const taskId = activeAgent.value?.task_id;
  if (!taskId) return false;
  return !!stoppingTaskIds.value?.[taskId];
});

const handleStop = async () => {
  const taskId = activeAgent.value?.task_id;
  if (!taskId || stopLoading.value) return;
  stopError.value = '';
  const result = await subAgentStore.terminateSubAgent(taskId);
  if (!result?.success) {
    stopError.value = result?.error || '停止失败';
  }
};

const displayItems = computed(() => {
  const order: string[] = [];
  const map = new Map<string, ActivityEntry>();
  for (const entry of activityEntries.value || []) {
    if (!entry) continue;
    const key = entry.id || `${entry.tool || 'tool'}-${entry.ts || order.length}`;
    if (!map.has(key)) {
      map.set(key, { ...entry });
      order.push(key);
    } else {
      map.set(key, { ...map.get(key), ...entry });
    }
  }

  return order.map((key) => {
    const item = map.get(key) || {};
    const state = normalizeStatus(item.status);
    const stateLabel = state === 'completed' ? '完成' : state === 'failed' ? '失败' : '进行中';
    return {
      key,
      state,
      stateLabel,
      text: buildText(item)
    };
  });
});
</script>
