#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'config/boot'
require_rel './models'
require_rel './services'
require_relative 'routes/device_routes'
require_relative 'routes/task_routes'
require_relative 'routes/task_execution_routes'
require_relative 'routes/setting_routes'
require_relative 'routes/script_routes'
require_relative 'routes/report_routes'
require_relative 'routes/custom_integration_routes'
# 应用设置
puts "6. 定义应用类..."
class NetCatClient < Sinatra::Base
  register Sinatra::Contrib
  
   configure do
     set :root, File.dirname(__FILE__)
     set :public_folder, File.join(root, 'public')
     set :views, File.join(root, 'views')
     set :sessions, true
     set :session_secret, ENV['SESSION_SECRET'] || 'netcat_client_development_secret_key_minimum_64_characters_required_2024'
     set :bind, '0.0.0.0'
     set :port, (ENV['PORT'] || 4567).to_i
     set :logging, true
     set :dump_errors, true
     set :show_exceptions, true
     set :server, 'puma'
     # 禁用主机授权保护以允许测试
     set :protection, except: :host_authorization
   end

   configure :development do
     if defined?(Sinatra::Reloader)
       puts "✓ Sinatra::Reloader 已加载，启用代码热重载"
       register Sinatra::Reloader
       also_reload 'models/*.rb'
       also_reload 'lib/*.rb'
       also_reload 'lib/script_execution_service/*.rb'
       also_reload 'services/*.rb'
       also_reload 'config/*.rb'
       also_reload './app.rb'

       puts "✓ 热重载配置完成：监控 models/, services/, config/ 目录"
     else
       puts "✗ Sinatra::Reloader 未加载，请检查环境变量 RACK_ENV=development"
     end
   end

   

   helpers do
    

    def ensure_utf8(str)
      return str if str.nil?
      str = str.to_s
      return str if str.encoding == Encoding::UTF_8 && str.valid_encoding?

      if str.encoding == Encoding::ASCII_8BIT
        str = str.force_encoding('UTF-8')
        return str if str.valid_encoding?
        str = str.force_encoding('GBK').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
      else
        str = str.encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
      end
      str.scrub('?')
    rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
      str.scrub('?').force_encoding('UTF-8')
    end

    
    # 确保 content_for 功能可用
    include Sinatra::ContentFor if defined?(Sinatra::ContentFor)

  end

  # 注册路由模块
  register DeviceRoutes
  register TaskRoutes
  register TaskExecutionRoutes
  register SettingRoutes
  register ScriptRoutes
  register ReportRoutes
  register CustomIntegrationRoutes

  # 前置过滤器
   before do
     # API 端点不设置默认 content_type
     unless request.path_info.start_with?('/api/')
       content_type :html, charset: 'utf-8'
     end
     # 检查API令牌是否已配置
     unless session[:api_token] || request.path_info =~ /^\/(setup|config|api\/test-connection|terms)/
       redirect '/setup' unless SETTINGS.api_token_configured?
     end
   end

  # 首页 - 重定向到任务列表
  get '/' do
    redirect '/tasks'
  end
  
  # 首页数据 API
  get '/api/dashboard' do
    content_type :json
    
    {
    }.to_json
  end
  
  

  # 脚本管理页面 (Vue)
  get '/scripts' do
    @active_page = 'scripts'
    erb :scripts, layout: true
  end

  # 升级管理页面
  get '/upgrade' do
    @active_page = 'upgrade'
    erb :upgrade, layout: true
  end

  # 服务条款页面
  get '/terms' do
    @page_title = '服务条款 - 清巡'
    @active_page = 'terms'
    erb :terms, layout: true
  end

  # 上传升级包
  post '/api/v1/upgrade-packages/upload' do
    content_type :json

    unless params[:file] && params[:file][:tempfile]
      return { success: false, error: '请选择要上传的升级包' }.to_json
    end

    begin
      uploaded_file = params[:file][:tempfile]
      original_filename = ensure_utf8(params[:file][:filename])

      # 保存到临时目录
      temp_dir = './tmp/upgrade_uploads'
      FileUtils.mkdir_p(temp_dir)
      safe_filename = original_filename.gsub(/[^\w\.\-]/, '_')
      temp_path = File.join(temp_dir, "#{SecureRandom.uuid}_#{safe_filename}")
      FileUtils.mv(uploaded_file.path, temp_path)

      { success: true, temp_path: temp_path, filename: original_filename }.to_json
    rescue StandardError => e
      LogService.error("上传升级包失败: #{e.message}") if defined?(LogService)
      status 500
      { success: false, error: e.message }.to_json
    end
  end

  # 部署升级包
  post '/api/v1/upgrade-packages/deploy' do
    content_type :json

    begin
      puts "[DEBUG-API] 开始部署请求"
      data = JSON.parse(request.body.read)
      temp_path = data['temp_path']
      puts "[DEBUG-API] temp_path: #{temp_path}"

      unless temp_path && File.exist?(temp_path)
        puts "[DEBUG-API] 升级包不存在"
        return { success: false, error: '升级包不存在或未上传' }.to_json
      end

      deployer = UpgradePackageDeployer.new
      puts "[DEBUG-API] 调用 deployer.deploy"
      result = deployer.deploy(temp_path)
      puts "[DEBUG-API] deploy 返回: #{result.inspect}"

      if result[:success]
        { success: true, record: result[:record] }.to_json
      else
        puts "[DEBUG-API] deploy 失败: #{result[:error]}"
        status 400
        { success: false, error: result[:error] }.to_json
      end
    rescue JSON::ParserError
      puts "[DEBUG-API] JSON 解析错误"
      status 400
      { success: false, error: '无效的JSON格式' }.to_json
    rescue StandardError => e
      puts "[DEBUG-API] 异常: #{e.message}"
      puts e.backtrace.join("\n")
      LogService.error("部署升级包失败: #{e.message}") if defined?(LogService)
      status 500
      { success: false, error: e.message }.to_json
    end
  end

  # 获取升级记录列表
  get '/api/v1/upgrade-records' do
    content_type :json
    records = UpgradeRecord.order(Sequel.desc(:created_at)).limit(100).all
    records.map(&:to_api_hash).to_json
  end

  # 升级管理页面 - 配置API令牌


   

   
end


# 运行应用（只有直接执行时才启动）
puts "DEBUG: __FILE__=#{__FILE__}, $0=#{$0}"
if __FILE__ == $0
  puts "Starting 清巡 server on 127.0.0.1:9000..."
  puts "8. 调用 NetCatClient.run!..."
  begin
    NetCatClient.run!
  rescue => e
    puts "服务器启动失败: #{e.class}: #{e.message}"
    puts e.backtrace.join("\n")
    exit 1
  end
  puts "9. 服务器已停止。"
end
