import { defineStore } from 'pinia';
import { useUiStore } from './ui';

interface SubAgent {
  task_id: string;
  agent_id?: string | number;
  status?: string;
  summary?: string;
  last_tool?: string;
  conversation_id?: string;
}

interface SubAgentState {
  subAgents: SubAgent[];
  pollTimer: ReturnType<typeof setInterval> | null;
}

export const useSubAgentStore = defineStore('subAgent', {
  state: (): SubAgentState => ({
    subAgents: [],
    pollTimer: null
  }),
  actions: {
    async fetchSubAgents() {
      try {
        const resp = await fetch('/api/sub_agents');
        if (!resp.ok) {
          throw new Error(await resp.text());
        }
        const data = await resp.json();
        if (data.success) {
          this.subAgents = Array.isArray(data.data) ? data.data : [];
        }
      } catch (error) {
        console.error('获取子智能体列表失败:', error);
      }
    },
    startPolling() {
      if (this.pollTimer) {
        return;
      }
      const uiStore = useUiStore();
      this.pollTimer = setInterval(() => {
        if (uiStore.panelMode === 'subAgents') {
          this.fetchSubAgents();
        }
      }, 5000);
    },
    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
      }
    },
    openSubAgent(agent: SubAgent) {
      if (!agent || !agent.task_id) {
        return;
      }
      const base = this.getBaseUrl();
      const parentConv = agent.conversation_id || '';
      const convSegment = this.stripConversationPrefix(parentConv);
      const agentLabel = agent.agent_id ? `sub_agent${agent.agent_id}` : agent.task_id;
      const pathSuffix = convSegment ? `/${convSegment}+${agentLabel}` : `/sub_agent/${agent.task_id}`;
      const url = `${base}${pathSuffix}`;
      window.open(url, '_blank');
    },
    stripConversationPrefix(conversationId: string) {
      if (!conversationId) return '';
      return conversationId.startsWith('conv_') ? conversationId.slice(5) : conversationId;
    },
    getBaseUrl() {
      const override = (window as any).SUB_AGENT_BASE_URL || (window as any).__SUB_AGENT_BASE_URL__;
      if (override && typeof override === 'string') {
        return override.replace(/\/$/, '');
      }
      const { protocol, hostname } = window.location;
      if (hostname && hostname.includes('agent.')) {
        const mappedHost = hostname.replace('agent.', 'subagent.');
        return `${protocol}//${mappedHost}`;
      }
      return `${protocol}//${hostname}:8092`;
    }
  }
});
