local M = {}

-- 导入依赖模块
local sched = sched or require("aubo").sched
local welding_common = require("welding_common")
local welding_config = require("welding_config")
local welding_arc = require("welding_arc")
local welding_motion = require("welding_motion")
local welding_weave = require("welding_weave")
local welding_communication = require("welding_communication")
local welding_resume = require("welding_resume")

-- 生成直线断续焊路径
function M.generateLineIntermittentPath(start_point, end_point, gap, segment_length, mode)
	local _ENV = sched.select_robot(1)

	-- 调用断续焊轨迹生成接口
	local line_result = welding_communication.getFunctionResult("LineStitchPath.getLineSegments", {
		{ start_point[1], start_point[2], start_point[3], start_point[4], start_point[5], start_point[6] },
		{ end_point[1], end_point[2], end_point[3], end_point[4], end_point[5], end_point[6] },
		gap,
		segment_length,
		mode,
	})

	for i, seg in ipairs(line_result) do
		print(string.format("Segment %d:", i))
		print("  start_point:", table.unpack(seg.start_point))
		print("  end_point:", table.unpack(seg.end_point))
		print("  arc_on:", seg.arc_on)
	end

	return line_result
end

-- 断续焊工艺处理
function M.intermittentWeldingProcess(
	start_point,
	end_point,
	inter_mode,
	weld_len,
	non_weld_len,
	motion_param,
	params,
	state,
	is_welding_endpoints,
	welder_param
)
	local _ENV = sched.select_robot(1)

	--生成断续焊路点
	local path_result = M.generateLineIntermittentPath(start_point, end_point, non_weld_len, weld_len, inter_mode)

	if not path_result or #path_result == 0 then
		log_error(welding_common.log_prefix .. "断续焊路径生成失败（空表）")
		return nil, "路径生成失败"
	end

	local segments = path_result

	-- 打印：路径生成结果
	log_info(welding_common.log_prefix .. "=== 断续焊路径生成结果 ===")
	log_info(welding_common.log_prefix .. string.format("生成总分段数: %d (含焊接段+空走段)", #segments))
	log_info(
		welding_common.log_prefix
			.. string.format(
				"路径起点（第一条线段）: %s",
				welding_motion.formatPoseString(segments[1].start_point)
			)
	)
	log_info(
		welding_common.log_prefix
			.. string.format(
				"路径终点（最后一条线段）: %s",
				welding_motion.formatPoseString(segments[#segments].end_point)
			)
	)

	-- 获取整个断续焊路径的起点（第一条线段的起点）
	local first_segment = segments[1]
	local first_start_point = first_segment.start_point

	local weld_speed = motion_param.welding_speed or 0.008
	local air_speed = params.motion_parameters.tool_speed or 0.025
	local weave = motion_param.weave or 0 -- 0表示无摆焊

	log_info(welding_common.log_prefix .. "=== 运动速度参数 ===")
	log_info(welding_common.log_prefix .. string.format("焊接速度: %.3f m/s", weld_speed))
	log_info(welding_common.log_prefix .. string.format("空走速度: %.3f m/s", air_speed))
	log_info(
		welding_common.log_prefix
			.. string.format(
				"焊接端点平滑半径: %.3f m (is_welding_endpoints: %s)",
				is_welding_endpoints and 0.0 or (params.blend_radius or 0.02),
				tostring(is_welding_endpoints)
			)
	)

	if weave ~= 0 then
		log_info(welding_common.log_prefix .. "=== 摆焊参数 ===")
		local weave_params = welding_weave.prepareWeaveParams(motion_param)
		welding_weave.printWeaveParams(weave_params) -- 摆焊参数打印
	end

	local _, first_execute_motion = welding_resume.resolveResumeExecutionState()
	welding_motion.generateMoveLine(
		first_start_point,
		air_speed,
		params,
		state,
		is_welding_endpoints,
		motion_param.weld_type,
		true,
		first_execute_motion
	)

	-- 执行断续焊（按state区分逻辑）
	local total_segments = #segments

	log_info(welding_common.log_prefix .. string.format("=== 开始执行断续焊（状态: %s） ===", state))
	if state == "raw_path_weld" then
		welding_arc.beginGroupedRecord()
		local ok, err = pcall(function()
			-- 实际焊接状态执行
			for i = 1, total_segments do
				local segment = segments[i]
				local current_waypoint = segment.end_point -- 线段终点作为目标点
				local last_waypoint = segment.start_point -- 线段起点作为起始点
				local is_weld_segment = segment.arc_on -- 焊接状态
				local is_last_segment = (i == total_segments)
				-- 按分段实时读取恢复态，避免在循环入口缓存状态导致命中恢复点后行为滞后。
				local _, segment_execute_motion = welding_resume.resolveResumeExecutionState()

				log_info(
					welding_common.log_prefix
						.. string.format(
							"执行分段 %d/%d: 类型=%s, 目标位姿=%s",
							i,
							total_segments,
							is_weld_segment and "焊接段" or "空走段",
							welding_motion.formatPoseString(current_waypoint)
						)
				)

				if not is_weld_segment then
					-- 空走段：熄弧，以空走速度移动
					if segment_execute_motion then
						welding_arc.stopArc()
					end
					welding_motion.generateMoveLine(
						current_waypoint,
						air_speed,
						params,
						state,
						is_welding_endpoints,
						motion_param.weld_type,
						true,
						segment_execute_motion
					)
				else
					-- 焊接段：起弧，根据摆焊模式执行
					if weave == 1 or weave == 2 then
						local weave_param = welding_weave.getSwingParams(motion_param)
						log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
						if segment_execute_motion then
							welding_config.updateWeldingParametSIntermittent(welder_param)
							welding_arc.startArc()
						end
						weaveStart(weave_param)
						welding_motion.generateMoveLine(
							current_waypoint,
							weld_speed,
							params,
							state,
							is_welding_endpoints,
							motion_param.weld_type,
							true,
							segment_execute_motion
						)
						weaveEnd()
					elseif weave == 3 then
						log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
						if segment_execute_motion then
							welding_config.updateWeldingParametSIntermittent(welder_param)
							welding_arc.startArc()
						end
						welding_weave.linearCrescentOscillation(
							motion_param,
							last_waypoint,
							current_waypoint,
							params,
							state
						)
					elseif weave == 4 then
						log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
						if segment_execute_motion then
							welding_config.updateWeldingParametSIntermittent(welder_param)
							welding_arc.startArc()
						end
						welding_weave.handleStraightWeave(motion_param, last_waypoint, current_waypoint, params, state)
					else
						if segment_execute_motion then
							log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
							welding_config.updateWeldingParametSIntermittent(welder_param)
							welding_arc.startArc()
						end
						welding_motion.generateMoveLine(
							current_waypoint,
							weld_speed,
							params,
							state,
							is_welding_endpoints,
							motion_param.weld_type,
							true,
							segment_execute_motion
						)
					end
				end

				-- 最后一段结束后熄弧
				-- 再次读取恢复态，确保“本段执行后刚好切到可执行”时熄弧动作不丢失。
				local _, stop_arc_execute_motion = welding_resume.resolveResumeExecutionState()
				if is_last_segment and stop_arc_execute_motion then
					welding_arc.stopArc()
					log_info(welding_common.log_prefix .. "=== 断续焊执行完成，已熄弧 ===")
				end
			end
		end)

		welding_arc.endGroupedRecord()
		if not ok then
			log_error(welding_common.log_prefix .. "执行失败: " .. tostring(state))
			return nil, "执行失败"
		end
	elseif state == "raw_path_sim" then
		-- 模拟状态：仅模拟运动，不起弧/熄弧
		for i = 1, total_segments do
			local segment = segments[i]
			local current_waypoint = segment.end_point
			local last_waypoint = segment.start_point
			local is_weld_segment = segment.arc_on
			local _, segment_execute_motion = welding_resume.resolveResumeExecutionState()

			log_info(
				welding_common.log_prefix
					.. string.format(
						"执行模拟分段 %d/%d: 类型=%s, 起点位姿=%s, 目标位姿=%s",
						i,
						total_segments,
						is_weld_segment and "焊接段（模拟）" or "空走段（模拟）",
						welding_motion.formatPoseString(last_waypoint),
						welding_motion.formatPoseString(current_waypoint)
					)
			)

			if not is_weld_segment then
				welding_motion.generateMoveLine(
					current_waypoint,
					air_speed,
					params,
					state,
					is_welding_endpoints,
					motion_param.weld_type,
					true,
					segment_execute_motion
				)
			else
				-- 焊接段：起弧，根据摆焊模式执行
				if weave == 1 or weave == 2 then
					local weave_param = welding_weave.getSwingParams(motion_param)
					log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
					weaveStart(weave_param)
					welding_motion.generateMoveLine(
						current_waypoint,
						weld_speed,
						params,
						state,
						is_welding_endpoints,
						motion_param.weld_type,
						true,
						segment_execute_motion
					)
					weaveEnd()
				elseif weave == 3 then
					log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
					welding_weave.linearCrescentOscillation(
						motion_param,
						last_waypoint,
						current_waypoint,
						params,
						state
					)
				elseif weave == 4 then
					log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
					welding_weave.handleStraightWeave(motion_param, last_waypoint, current_waypoint, params, state)
				else
					log_info(welding_common.log_prefix .. "摆焊启动，模式=" .. weave)
					welding_motion.generateMoveLine(
						current_waypoint,
						weld_speed,
						params,
						state,
						is_welding_endpoints,
						motion_param.weld_type,
						true,
						segment_execute_motion
					)
				end
			end
		end
	elseif state == "raw_point_sim" then
		-- 快速模拟：仅移动
		for i = 1, total_segments do
			local segment = segments[i]
			local current_waypoint = segment.end_point
			local is_weld_segment = segment.arc_on
			local _, segment_execute_motion = welding_resume.resolveResumeExecutionState()

			if not is_weld_segment then
				welding_motion.generateMoveLine(
					current_waypoint,
					air_speed,
					params,
					state,
					is_welding_endpoints,
					motion_param.weld_type,
					true,
					segment_execute_motion
				)
			else
				welding_motion.generateMoveLine(
					current_waypoint,
					weld_speed,
					params,
					state,
					is_welding_endpoints,
					motion_param.weld_type,
					true,
					segment_execute_motion
				)
			end
		end
	else
		log_error(welding_common.log_prefix .. "未知状态: " .. tostring(state))
		return nil, "未知状态"
	end

	return true, "执行完成"
end

return M
