import { ref } from 'vue';
import { useVueFlow, type Node, type Edge } from '@vue-flow/core';

/**
 * 画布操作 Hook
 */
export function useCrewCanvas() {
	const {
		nodes, edges, addNodes, removeNodes,
		addEdges, removeEdges, fitView,
		onConnect, onNodeDragStop,
	} = useVueFlow();

	const masterAgentId = ref<number | null>(null);

	function addAgentNode(agent: any, position?: { x: number; y: number }) {
		const id = `agent-${agent.id}`;
		if (nodes.value.find(n => n.id === id)) return;
		const node: Node = {
			id,
			type: 'crew-agent',
			position: position || { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
			data: {
				agentId: agent.id, name: agent.name, label: agent.label,
				icon: agent.icon, description: agent.description,
				role: '', groupName: '',
				isMaster: agent.id === masterAgentId.value,
			},
		};
		addNodes([node]);
	}

	function removeAgentNode(agentId: number) {
		const nodeId = `agent-${agentId}`;
		const node = nodes.value.find(n => n.id === nodeId);
		if (node) removeNodes([node]);
	}

	function setMasterAgent(agentId: number) {
		masterAgentId.value = agentId;
		nodes.value.forEach(n => {
			if (n.data) n.data.isMaster = n.data.agentId === agentId;
		});
	}

	function serializeCanvas() {
		return {
			nodes: nodes.value.map(n => ({
				id: n.id, type: n.type, position: n.position, data: n.data,
			})),
			edges: edges.value.map(e => ({
				id: e.id, source: e.source, target: e.target, data: e.data,
			})),
		};
	}

	function deserializeCanvas(canvasData: any) {
		if (!canvasData?.nodes) return;
		removeNodes(nodes.value);
		removeEdges(edges.value);
		addNodes(canvasData.nodes.map((n: any) => ({ ...n, type: n.type || 'crew-agent' })));
		if (canvasData.edges?.length) addEdges(canvasData.edges);
		setTimeout(() => fitView({ padding: 0.2 }), 100);
	}

	function extractMembers() {
		return nodes.value
			.filter(n => n.data?.agentId)
			.map(n => ({
				agentId: n.data.agentId,
				role: n.data.role || '',
				canvasPosition: n.position,
				groupName: n.data.groupName || '',
			}));
	}

	return {
		nodes, edges, masterAgentId,
		addAgentNode, removeAgentNode, setMasterAgent,
		serializeCanvas, deserializeCanvas, extractMembers,
		onConnect, onNodeDragStop, fitView,
	};
}
