import { getToken } from "@/api/request.js";

const CHART_INTERPRETATION_PATH = "/aiAnalysis/chart_interpretation";

/**
 * 从接口各类返回结构中取出「解读」纯文本（含流式拼出的 ```json [...] ``` 字符串）
 * @param {unknown} raw
 * @returns {string}
 */
export function extractChartInterpretationText(raw) {
	if (raw == null || raw === "") {
		return "";
	}
	if (Array.isArray(raw)) {
		const first = raw[0];
		if (first && typeof first === "object") {
			const v = first["解读"] ?? first.interpretation;
			if (v != null && String(v).trim()) {
				return String(v).trim();
			}
		}
		return "";
	}
	if (typeof raw === "object") {
		if (Array.isArray(raw.data)) {
			return extractChartInterpretationText(raw.data);
		}
		if (typeof raw.data === "string") {
			return extractChartInterpretationText(raw.data);
		}
		if (typeof raw.text === "string") {
			return extractChartInterpretationText(raw.text);
		}
		const v = raw["解读"] ?? raw.interpretation;
		if (v != null) {
			return String(v).trim();
		}
		for (const key of ["result", "content", "items", "list"]) {
			if (Array.isArray(raw[key])) {
				const t = extractChartInterpretationText(raw[key]);
				if (t) {
					return t;
				}
			}
		}
		return "";
	}
	if (typeof raw === "string") {
		const t = raw.trim();
		if (!t) {
			return "";
		}
		try {
			return extractChartInterpretationText(JSON.parse(t));
		} catch {
			/* 非纯 JSON */
		}
		const unfenced = t
			.replace(/^```(?:json)?\s*/i, "")
			.replace(/```\s*$/i, "")
			.trim();
		try {
			return extractChartInterpretationText(JSON.parse(unfenced));
		} catch {
			/* 继续尝试截取数组 */
		}
		const arrMatch = unfenced.match(/\[\s*\{[\s\S]*"解读"[\s\S]*\}\s*\]/);
		if (arrMatch) {
			try {
				return extractChartInterpretationText(JSON.parse(arrMatch[0]));
			} catch {
				/* ignore */
			}
		}
		const byRegex = extractInterpretationByRegex(t);
		if (byRegex) {
			return byRegex;
		}
		return "";
	}
	return "";
}

/**
 * 从非严格 JSON 的文本中用正则提取「解读」字段（流式拼完后仍解析失败时的兜底）
 * @param {string} s
 * @returns {string}
 */
function extractInterpretationByRegex(s) {
	if (!s || typeof s !== "string") {
		return "";
	}
	const m = s.match(/"解读"\s*:\s*"((?:[^"\\]|\\.)*)"/);
	if (!m || !m[1]) {
		return "";
	}
	return m[1].replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
}

/**
 * 解析 SSE 文本行（流式或整包响应体）
 * @param {string} fullText
 * @returns {string}
 */
function parseSseChartInterpretationLines(fullText) {
	let textFragments = "";
	let lastFromArray = "";
	/** 单行 JSON.parse 失败的 data 片段，多为跨多行的同一 JSON（如数组） */
	const unparsedPayloads = [];

	const lines = fullText.split(/\r?\n/);
	for (const line of lines) {
		const trimmed = line.trim();
		if (!trimmed.startsWith("data:")) {
			continue;
		}
		const payload = trimmed.slice(5).trim();
		if (!payload || payload === "[DONE]") {
			continue;
		}
		let parsed;
		try {
			parsed = JSON.parse(payload);
		} catch {
			unparsedPayloads.push(payload);
			continue;
		}
		if (Array.isArray(parsed)) {
			const t = extractChartInterpretationText(parsed);
			if (t) {
				lastFromArray = t;
			}
			continue;
		}
		if (parsed && typeof parsed.text === "string") {
			textFragments += parsed.text;
		}
	}

	if (lastFromArray) {
		return lastFromArray;
	}

	/* 合并跨多行 data: 的 JSON（例如 data: [ 、 data: { 、 data: "图表标题"…） */
	if (unparsedPayloads.length > 0) {
		const joinedNewline = unparsedPayloads.join("\n").trim();
		for (const candidate of [joinedNewline, unparsedPayloads.join("").trim()]) {
			if (!candidate) {
				continue;
			}
			try {
				const t = extractChartInterpretationText(JSON.parse(candidate));
				if (t) {
					return t;
				}
			} catch {
				/* ignore */
			}
			const t2 = extractChartInterpretationText(candidate);
			if (t2) {
				return t2;
			}
			const t3 = extractInterpretationByRegex(candidate);
			if (t3) {
				return t3;
			}
		}
	}

	const fromFragments = extractChartInterpretationText(textFragments);
	if (fromFragments) {
		return fromFragments;
	}
	const fragRegex = extractInterpretationByRegex(textFragments);
	if (fragRegex) {
		return fragRegex;
	}
	return extractChartInterpretationText(textFragments.trim());
}

/**
 * @param {ReadableStream<Uint8Array> | null} body
 * @param {(chunk: string) => void} [onDelta]
 * @returns {Promise<string>}
 */
async function readSseChartInterpretationStream(body, onDelta) {
	if (!body) {
		return "";
	}
	const reader = body.getReader();
	const decoder = new TextDecoder();
	let all = "";
	let lastPushed = "";
	while (true) {
		const { done, value } = await reader.read();
		if (done) {
			break;
		}
		all += decoder.decode(value, { stream: true });
		const now = parseSseChartInterpretationLines(all);
		if (now && now !== lastPushed) {
			lastPushed = now;
			onDelta?.(now);
		}
	}
	all += decoder.decode();
	const fin = parseSseChartInterpretationLines(all);
	if (fin && fin !== lastPushed) {
		onDelta?.(fin);
	}
	return fin;
}

/**
 * POST 图表解读：支持 SSE（data: {"text":"..."} / data: [...]）与普通 JSON
 * @param {Record<string, unknown>} body
 * @param {(interpretation: string) => void} [onInterpretationDelta] 流式过程中有可读解读时回调
 * @returns {Promise<string>} 解读正文
 */
export async function fetchChartInterpretation(body, onInterpretationDelta) {
	const headers = {
		"Content-Type": "application/json",
		Accept: "text/event-stream, application/json, text/plain, */*"
	};
	const token = getToken();
	if (token) {
		headers.token = token;
	}
	const aiApiKey = import.meta.env.VITE_AI_ANALYSIS_API_KEY;
	if (aiApiKey) {
		headers["X-API-Key"] = aiApiKey;
	}

	const res = await fetch(CHART_INTERPRETATION_PATH, {
		method: "POST",
		headers,
		body: JSON.stringify(body)
	});

	if (!res.ok) {
		const errText = await res.text().catch(() => "");
		throw new Error(errText || `Request failed with status ${res.status}`);
	}

	const contentType = res.headers.get("content-type") || "";

	if (contentType.includes("text/event-stream") || contentType.includes("event-stream")) {
		return readSseChartInterpretationStream(res.body, onInterpretationDelta);
	}

	const text = await res.text();
	if (/^\s*data:/m.test(text)) {
		const out = parseSseChartInterpretationLines(text);
		if (out) {
			onInterpretationDelta?.(out);
		}
		return out;
	}
	let parsed;
	try {
		parsed = JSON.parse(text);
	} catch {
		const extracted = extractChartInterpretationText(text);
		return extracted || text.trim();
	}
	const extracted = extractChartInterpretationText(parsed);
	if (extracted) {
		return extracted;
	}
	if (typeof parsed === "string") {
		return extractChartInterpretationText(parsed) || parsed;
	}
	return extractChartInterpretationText(text) || text.trim();
}

/**
 * 图表解读（POST /chart_interpretation），兼容流式 SSE 与一次性 JSON
 * @param {{ text: string }} data
 * @param {{ onInterpretationDelta?: (s: string) => void }} [options]
 * @returns {Promise<string>} 解读纯文本
 */
export async function getChartAnalysis(data, options = {}) {
	const { onInterpretationDelta } = options;
	return fetchChartInterpretation(data, onInterpretationDelta);
}
