import { ref } from "vue";

export const useChartInterpretation = () => {
	const loading = ref(false);
	const interpretation = ref("");
	const error = ref(null);

	const interpret = async text => {
		loading.value = true;
		error.value = null;
		interpretation.value = "";

		try {
			const response = await fetch("/aiAnalysis/chart_interpretation", {
				method: "POST",
				headers: {
					"X-API-Key": "aircasKEY19491001",
					"Content-Type": "application/json"
				},
				body: JSON.stringify({ text })
			});

			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}

			const reader = response.body.getReader();
			const decoder = new TextDecoder();
			let buffer = "";

			while (true) {
				const { done, value } = await reader.read();
				if (done) break;

				buffer += decoder.decode(value, { stream: true });
				const lines = buffer.split("\n");
				buffer = lines.pop() || "";

				for (const line of lines) {
					if (line.startsWith("data: ")) {
						const content = line.substring(6);
						const textMatch = content.match(/"解读":\s*"([^"]*)"/);
						if (textMatch && textMatch[1]) {
							interpretation.value = textMatch[1];
						}
					}
				}
			}
		} catch (err) {
			error.value = err.message || "AI 解读失败";
			console.error("AI Chart Interpretation Error:", err);
		} finally {
			loading.value = false;
		}
	};

	return {
		loading,
		interpretation,
		error,
		interpret
	};
};
