/**
 * 按章节适用车型绑定，从整份合同 HTML 中移除未命中的附件章节。
 */
import { sectionBindingsMatchOrder } from './vehicle-binding-utils.js';

var ATTACHMENT_SECTIONS = [
	{ key: 'lease_order', markers: ['<b>1：租赁订单 </b>', '附件 1：租赁订单', '附件1：租赁订单', '1：租赁订单'] },
	{ key: 'vehicle_cost', markers: ['附件2:车辆产生的费用', '附件2：车辆产生的费用', '<b>附件2：车辆产生的费用</b>'] },
	{ key: 'safety_notice', markers: ['附件3:安全责任告知书', '附件3：安全责任告知书', '<b>附件3：安全责任告知书</b>'] },
	{ key: 'dynamic_supervision', markers: ['附件4：重型普通货运车辆租赁动态监管责任告知与确认书', '附件4:'] },
	{ key: 'safety_commitment', markers: ['<b>附件5：</b>', '<b>安全责任承诺书</b></p><p class="ct-word-body">为严格落实', '附件5：', '附件5:'] },
	{ key: 'vehicle_spec', markers: ['<b>附件6：车辆使用规范和驾驶员要求</b>', '附件6：车辆使用规范和驾驶员要求', '附件6:'] },
	{ key: 'authorization', markers: ['font: 28.0px Times; color: #000000"><b>授权委托书</b>', '<b>授权委托书</b></p><p class="ct-word-body">致：', '<b>授权委托书</b><b></b></p><p class="ct-word-body">致：'] },
	{ key: 'safety_agreement', markers: ['data-risk-redline="1"><b>安全责任协议</b></span></p>', '<b>安全责任协议</b></p><p class="ct-word-body"><br></p><p class="ct-word-body"><b>甲方（出租方）：</b>', '<b>安全责任协议</b></p><p class="ct-word-body"><br></p>'] },
];

function isValidSectionMarkerMatch(source, index, marker) {
	if (index < 0) return false;
	var text = String(source || '');
	var before = text.slice(Math.max(0, index - 8), index);
	var after = text.slice(index, index + String(marker || '').length + 12);
	if (/[（(]$/.test(before)) return false;
	if (/、$/.test(before)) return false;
	if (/^《/.test(after.slice(String(marker).length))) return false;
	var nearby = text.slice(Math.max(0, index - 24), index + String(marker).length + 24);
	if (/详见.{0,20}附件/.test(nearby)) return false;
	if (/以附件/.test(nearby)) return false;
	if (String(marker).length <= 10 && !/<b>/.test(nearby)) return false;
	return true;
}

function findFirstMarker(source, markers) {
	var text = String(source || '');
	var best = -1;
	(markers || []).forEach(function (marker) {
		var from = 0;
		while (from < text.length) {
			var idx = text.indexOf(marker, from);
			if (idx < 0) break;
			if (isValidSectionMarkerMatch(text, idx, marker)) {
				if (best < 0 || idx < best) best = idx;
				break;
			}
			from = idx + 1;
		}
	});
	return best;
}

function collectSectionRanges(html) {
	var source = String(html || '');
	var points = ATTACHMENT_SECTIONS.map(function (section) {
		return {
			key: section.key,
			index: findFirstMarker(source, section.markers),
		};
	}).filter(function (point) { return point.index >= 0; });

	points.sort(function (a, b) { return a.index - b.index; });

	return points.map(function (point, idx) {
		var next = points[idx + 1];
		return {
			key: point.key,
			start: point.index,
			end: next ? next.index : source.length,
		};
	});
}

export function applyAttachmentSectionVehicleFilter(html, sectionVehicleBindings, vehicleKeys) {
	var source = String(html || '');
	if (!source) return source;

	var bindingsMap = sectionVehicleBindings || {};
	var ranges = collectSectionRanges(source);
	if (!ranges.length) return source;

	var removeMask = new Array(source.length);
	ranges.forEach(function (range) {
		var bindings = bindingsMap[range.key] || [];
		if (sectionBindingsMatchOrder(bindings, vehicleKeys)) return;
		for (var i = range.start; i < range.end; i++) {
			removeMask[i] = true;
		}
	});

	if (!removeMask.some(Boolean)) return source;

	var out = '';
	for (var pos = 0; pos < source.length; pos++) {
		if (!removeMask[pos]) out += source.charAt(pos);
	}
	return out;
}
