import { computed, type Ref } from 'vue';
import type { AuditOrderDetail } from '../types/index.d';

/** 风险雷达5维度 */
export interface RiskDimension {
	label: string;
	key: string;
	score: number; // 0-100
}

/** stepType → 维度映射 */
const DIMENSION_MAP: Record<string, string> = {
	id_card_ocr: 'identity',
	invoice_ocr: 'identity',
	vehicle_invoice_ocr: 'identity',
	driving_license_ocr: 'identity',
	data_compare: 'consistency',
	rule_check: 'compliance',
	insure_audit: 'compliance',
	claim_audit: 'compliance',
	damage_detect: 'imageQuality',
	llm_judge: 'overall',
};

const DIMENSION_LABELS: Record<string, string> = {
	identity: '证件真实性',
	consistency: '数据一致性',
	compliance: '规则合规性',
	imageQuality: '图片质量',
	overall: '综合风险',
};

const DIMENSION_ORDER = ['identity', 'consistency', 'compliance', 'imageQuality', 'overall'];

/**
 * 从 insure_audit 的 outputData 中提取子维度分数
 * insure_audit 内部包含身份证比对(规则4)和发票比对(规则5)，可映射到 consistency 维度
 */
function extractInsureAuditSubScores(step: AuditOrderDetail): Record<string, number> | null {
	const output = step.outputData;
	if (!output || step.stepType !== 'insure_audit') return null;

	// 解析 outputData
	const data = typeof output === 'string' ? (() => { try { return JSON.parse(output); } catch { return null; } })() : output;
	if (!data?.ruleCheckResults) return null;

	const rules = data.ruleCheckResults;
	// 规则4(身份证比对) + 规则5(发票比对) → consistency 维度
	const consistencyRules = rules.filter((r: any) => r.ruleId === 4 || r.ruleId === 5);
	if (consistencyRules.length > 0) {
		const passCount = consistencyRules.filter((r: any) => r.passed).length;
		return {
			consistency: Math.round((passCount / consistencyRules.length) * 100),
		};
	}
	return null;
}

/**
 * 推断步骤分数：优先用 score 字段，否则从 passed/outputData 推断
 */
function inferStepScore(step: AuditOrderDetail): number | null {
	// 有显式 score 直接用
	if (step.score != null) return Number(step.score);

	// 从 outputData 中提取 score（insure_audit/claim_audit 等 Skill 返回的 JSON 里有 score）
	if (step.outputData) {
		const data = typeof step.outputData === 'string'
			? (() => { try { return JSON.parse(step.outputData as any); } catch { return null; } })()
			: step.outputData;
		if (data?.score != null) return Number(data.score);
	}

	// 有 passed 字段：1=通过(90分) 0=不通过(20分) 2=转人工(50分)
	if (step.passed != null) {
		if (step.passed === 1) return 90;
		if (step.passed === 0) return 20;
		if (step.passed === 2) return 50;
	}

	// OCR 等步骤：有 outputData 且执行成功 → 视为通过
	if (step.outputData && step.duration) {
		const data = typeof step.outputData === 'string'
			? (() => { try { return JSON.parse(step.outputData as any); } catch { return null; } })()
			: step.outputData;
		if (data?.success !== false) return 85;
	}

	return null;
}

/**
 * 从审核步骤聚合5维风险评分
 */
export function useRiskScore(details: Ref<AuditOrderDetail[]>) {
	const dimensions = computed<RiskDimension[]>(() => {
		const grouped: Record<string, number[]> = {};
		DIMENSION_ORDER.forEach((k) => (grouped[k] = []));

		for (const step of details.value) {
			const dim = DIMENSION_MAP[step.stepType];
			if (dim) {
				const score = inferStepScore(step);
				if (score != null) {
					grouped[dim].push(score);
				}
			}

			// 从 insure_audit 提取子维度分数
			const subScores = extractInsureAuditSubScores(step);
			if (subScores) {
				for (const [key, score] of Object.entries(subScores)) {
					if (grouped[key] && !grouped[key].length) {
						grouped[key].push(score);
					}
				}
			}
		}

		return DIMENSION_ORDER.map((key) => ({
			label: DIMENSION_LABELS[key],
			key,
			score: grouped[key].length
				? Math.round(grouped[key].reduce((a, b) => a + b, 0) / grouped[key].length)
				: 0,
		}));
	});

	return { dimensions };
}
