# frozen_string_literal: true

$stdout.sync = true
$stderr.sync = true
puts "=== Starting app ==="
puts "PID: #{Process.pid}"
# Signal.trap('TERM') { puts "Caught SIGTERM from #{Signal.list['TERM']}"; exit }
# at_exit { puts "=== Exiting: #{$!} ===" }

require 'require_all'
require './lib/port_cleaner'

# 清理 9000 (Sinatra) 和 90008 (IPC) 端口
# 注意：在 Docker 容器中不执行，避免杀掉主进程
PortCleaner.clean_port(9000) unless ENV['DOCKER_CONTAINER'] == 'true'
PortCleaner.clean_port(90008)
sleep 0.2 # 等待端口完全释放

# 手动加载依赖，避免自动启动问题
# require 'bundler/setup'
# puts "bundler/setup done"
# Bundler.setup(:default)
require 'sinatra/base'

require 'sinatra/contrib'
if ENV['RACK_ENV'] == 'development'
  require 'sinatra/reloader'
  puts "✓ sinatra/reloader 已加载 (开发环境)"
else
  puts "✗ sinatra/reloader 未加载 (当前环境: #{ENV['RACK_ENV'] || '未设置'})"
end
require 'json'
require 'csv'
require 'sinatra/content_for'
require 'uri'
require 'securerandom'
require 'dotenv/load'
require 'pry'
require './lib/net_cat'
require './lib/telnet_device'
# 加载任务执行相关库
require_relative '../lib/task_execution_manager'
require_relative '../lib/thread_pool_executor'
require_relative '../lib/task_directory_preparer'
require_relative '../lib/device_login_handler'
require_relative '../lib/script_executor'
require_relative '../lib/device_execution_processor'
require_relative '../lib/task_finalizer'
require_relative '../lib/task_execution_coordinator'
puts "3.2 任务执行库加载完成"
# 加载任务执行相关库
require_relative '../lib/task_execution_manager'
require_relative '../lib/thread_pool_executor'
require_relative '../lib/task_execution_coordinator'
puts "3.2 任务执行库加载完成"
# 加载日志服务
require_relative '../services/log_service'
# 设置日志级别为 debug，方便调试同步问题
LogService.instance.configure(level: :debug)
puts "3.1 日志服务加载完成 (DEBUG级别已启用)"
require_relative '../config/settings'
require_relative '../config/database'
puts "3. 配置加载完成"

# 全局设置实例
SETTINGS = Settings.instance


# 显示环境信息
puts "当前环境: RACK_ENV=#{ENV['RACK_ENV'] || '未设置'}"

# 停止任务执行协调器和脚本执行服务
at_exit do
  puts "\n正在停止任务执行协调器..."
  begin
    TaskExecutionCoordinator.instance.stop(wait: false)
    puts "任务执行协调器已停止"
  rescue => e
    puts "停止任务执行协调器失败: #{e.message}"
  end
  
  puts "\n正在停止脚本执行服务..."
  if $script_execution_service
    begin
      ScriptExecutionService::ProcessManager.stop_all
      puts "脚本执行服务已停止"
    rescue => e
      puts "停止脚本执行服务失败: #{e.message}"
    end
  end
end