# frozen_string_literal: true

# 任务执行相关路由
module TaskExecutionRoutes
  def self.registered(app)
    # 启动任务执行
    app.post '/tasks/:id/start' do
      @task = LocalTask[params[:id]]
      halt 404, '任务不存在' unless @task

      # 创建新的执行记录
      @execution = @task.create_new_execution!

      @execution.start!

      # 使用新的任务执行协调器提交任务
      coordinator = TaskExecutionCoordinator.instance
      coordinator.submit_task(@task, @execution)

      redirect "/tasks/#{@task.id}/vue"
    end

    # 获取所有正在执行的任务状态（从内存读取）
    app.get '/api/tasks/running' do
      content_type :json
      manager = TaskExecutionManager.instance
      { tasks: manager.get_all_running_tasks }.to_json
    end

    # 获取单个执行任务的状态（从内存读取，优先使用内存，没有则从数据库）
    app.get '/api/executions/:id/status' do
      content_type :json
      execution_id = params[:id]

      manager = TaskExecutionManager.instance
      task_state = manager.get_task(execution_id)

      if task_state
        task_state.to_json
      else
        # 内存中没有，从数据库读取
        execution = LocalTaskExecution[execution_id]
        halt 404, { error: '执行记录不存在' }.to_json unless execution
        execution.to_api_hash.to_json
      end
    end

    # 读取脚本日志文件
    app.get '/api/executions/:id/logs/:device_ip/:script_name' do
      content_type :json
      execution_id = params[:id]
      device_ip = params[:device_ip]
      script_name = params[:script_name]

      execution = LocalTaskExecution[execution_id]
      halt 404, { error: '执行记录不存在' }.to_json unless execution

      # 先从 execution_units 中查找脚本的 log_file_path
      log_file_path = nil
      units = execution.get_execution_units
      units.each do |dev_id, dev_info|
        scripts = dev_info['scripts'] || dev_info[:scripts] || {}
        scripts.each do |script_id, script_info|
          s_name = script_info['script_name'] || script_info[:script_name] || script_info['name'] || script_info[:name]
          if s_name == script_name
            log_file_path = script_info['log_file_path'] || script_info[:log_file_path]
            break
          end
        end
        break if log_file_path
      end

      # 如果没找到，再构建路径
      unless log_file_path
        log_file_path = FilePathUtils.devlog_file_path(
          execution.task_dir_name,
          device_ip,
          script_name
        )
      end

      if File.exist?(log_file_path)
        content = File.read(log_file_path)
        { log: content, success: true }.to_json
      else
        { log: '', success: false, error: '日志文件不存在' }.to_json
      end
    end
  end
end