import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useCool } from '/@/cool';

/**
 * Crew 编排状态管理
 */
export const useCrewStore = defineStore('agent-crew', () => {
	const { service } = useCool();

	const crewList = ref<any[]>([]);
	const currentCrew = ref<any>(null);
	const currentMembers = ref<any[]>([]);
	const availableAgents = ref<any[]>([]);

	async function loadCrewList() {
		const res = await service.netaclaw.crew.list();
		crewList.value = res || [];
	}

	async function loadCrewDetail(crewId: number) {
		const res = await service.netaclaw.crew.detail({ id: crewId });
		currentCrew.value = res;
		currentMembers.value = res?.members || [];
		return res;
	}

	async function loadAvailableAgents() {
		const res = await service.netaclaw.agent.page({ page: 1, size: 1000 });
		availableAgents.value = res?.list || [];
	}

	async function saveCanvas(crewId: number, canvasData: any, members: any[], delegateHints: any) {
		const masterAgentId = currentCrew.value?.masterAgentId;
		await service.netaclaw.crew.saveCanvas({ crewId, canvasData, members, delegateHints, masterAgentId });
	}

	async function createCrew(data: any) {
		const res = await service.netaclaw.crew.add(data);
		await loadCrewList();
		return res;
	}

	async function publish(crewId: number) {
		await service.netaclaw.crew.publish({ id: crewId });
		await loadCrewDetail(crewId);
	}

	async function unpublish(crewId: number) {
		await service.netaclaw.crew.unpublish({ id: crewId });
		await loadCrewDetail(crewId);
	}

	const isMember = computed(() => {
		const ids = new Set(currentMembers.value.map((m: any) => m.agentId));
		return (agentId: number) => ids.has(agentId);
	});

	return {
		crewList, currentCrew, currentMembers, availableAgents,
		loadCrewList, loadCrewDetail, loadAvailableAgents,
		saveCanvas, createCrew, publish, unpublish, isMember,
	};
});
