# frozen_string_literal: true

# 自定义集成代码相关路由
module CustomIntegrationRoutes
  def self.registered(app)
    # 获取自定义集成代码状态
    app.get '/api/custom-integration/status' do
      content_type :json

      begin
        status = CustomIntegrationCode.status
        {
          success: true,
          data: status
        }.to_json
      rescue StandardError => e
        {
          success: false,
          message: "获取状态失败: #{e.message}"
        }.to_json
      end
    end

    # 获取当前使用的代码
    app.get '/api/custom-integration/code' do
      content_type :json

      begin
        record = CustomIntegrationCode.current
        code = record&.current_code || '# 自定义集成代码不可用'
        using_user = record&.using_user_version? || false

        {
          success: true,
          data: {
            code: code,
            using_user_version: using_user,
            server_version_hash: record&.server_version_hash,
            user_version_hash: record&.user_version_hash,
            server_updated_at: record&.server_updated_at&.iso8601,
            user_updated_at: record&.user_updated_at&.iso8601,
            last_synced_at: record&.last_synced_at&.iso8601
          }
        }.to_json
      rescue StandardError => e
        {
          success: false,
          message: "获取代码失败: #{e.message}"
        }.to_json
      end
    end

    # 获取服务器版本代码（只读）
    app.get '/api/custom-integration/server-code' do
      content_type :json

      begin
        record = CustomIntegrationCode.current
        code = record&.server_code || '# 服务器版本不可用'
        version_hash = record&.server_version_hash

        {
          success: true,
          data: {
            code: code,
            version_hash: version_hash,
            updated_at: record&.server_updated_at&.iso8601
          }
        }.to_json
      rescue StandardError => e
        {
          success: false,
          message: "获取服务器版本代码失败: #{e.message}"
        }.to_json
      end
    end

    # 保存用户版本代码
    app.put '/api/custom-integration/code' do
      content_type :json

      request.body.rewind
      body = JSON.parse(request.body.read) rescue {}
      code = body['code']
      notes = body['notes']

      if code.nil? || code.empty?
        return {
          success: false,
          message: "代码内容不能为空"
        }.to_json
      end

      begin
        # 检查是否启用自定义集成
        unless Settings.instance.get(:custom_integration, :enabled)
          return {
            success: false,
            message: "自定义集成功能未启用"
          }.to_json
        end

        # 检查语法（如果启用）
        if Settings.instance.get(:custom_integration, :security, :validate_syntax)
          # 这里可以添加简单的Ruby语法检查
          # 暂时跳过，后续实现
        end

        puts "[CustomIntegration] 保存用户版本，代码长度: #{code.length}, 备注: #{notes || '无'}"
        success = CustomIntegrationCode.save_user(code, notes)

        if success
          puts "[CustomIntegration] 保存成功"
          {
            success: true,
            message: "用户版本代码已保存"
          }.to_json
        else
          puts "[CustomIntegration] 保存失败"
          {
            success: false,
            message: "保存用户版本代码失败"
          }.to_json
        end
      rescue StandardError => e
        {
          success: false,
          message: "保存代码失败: #{e.message}"
        }.to_json
      end
    end

    # 恢复使用服务器版本（清空用户版本）
    app.delete '/api/custom-integration/code' do
      content_type :json

      begin
        CustomIntegrationCode.clear_user!

        {
          success: true,
          message: "已恢复使用服务器版本"
        }.to_json
      rescue StandardError => e
        {
          success: false,
          message: "恢复服务器版本失败: #{e.message}"
        }.to_json
      end
    end

    # 获取编辑历史
    app.get '/api/custom-integration/history' do
      content_type :json

      begin
        history = CustomIntegrationCode.history
        # 调试日志
        puts "[CustomIntegration] 获取历史记录，数量: #{history.length}"
        history.each_with_index do |h, i|
          puts "  历史#{i+1}: #{h['version_hash'][0..8]}... - #{h['timestamp']} - 代码长度: #{h['length']}"
        end
        {
          success: true,
          data: history
        }.to_json
      rescue StandardError => e
        {
          success: false,
          message: "获取历史记录失败: #{e.message}"
        }.to_json
      end
    end

    # 手动同步服务器版本（从云端）
    app.post '/api/custom-integration/sync' do
      content_type :json

      begin
        # 检查是否启用自定义集成
        unless Settings.instance.get(:custom_integration, :enabled)
          return {
            success: false,
            message: "自定义集成功能未启用"
          }.to_json
        end

        # 调用云客户端同步
        client = CloudClient.instance
        result = client.sync_custom_integration_code

        if result[:success]
          {
            success: true,
            message: "同步成功",
            data: {
              version_hash: result[:version_hash],
              updated_at: result[:updated_at]
            }
          }.to_json
        else
          {
            success: false,
            message: "同步失败: #{result[:error]}"
          }.to_json
        end
      rescue StandardError => e
        {
          success: false,
          message: "同步失败: #{e.message}"
        }.to_json
      end
    end

    # 自定义集成代码管理页面
    app.get '/custom-integration' do
      @active_page = 'custom_integration'
      erb :custom_integration, layout: true
    end
  end
end