require 'json'
require "vips"
require "image_processing/vips"

namespace :seed_tasks do

  ## Build ID Card Information Tables

  desc "Build Initial Plan Templates"
  # rake seed_tasks:build_plan_templates
  task build_plan_templates: :environment do
    puts "Importing Plan Templates"
    file_path = Rails.root.join('seed_docs', 'Standard Level360 Plans.pdf')
    reader = PDF::Reader.new(file_path)
    pages = []
    reader.pages.each do |page|
      rows = []
      text = page.text
      lines = text.split("\n")

      lines.each do |line|
        cells = line.strip.split(/\s{2,}|\t/)
        rows << cells if cells.size > 1
      end
      pages << rows
    end

    pages.each do |page_rows|
      title_row = page_rows.first
      title_row.each_with_index do |plan, index|
          next if index == 0
          plan_items = page_rows.map { |row| row[index] }
          plan_items.shift

          puts "-- #{plan}"
          plan = IdCard::Plan.create!(title: plan, template: true)
          doc_to_sequence_map = {
              0 => 4,
              1 => 5,
              2 => 6,
              3 => 7,
              4 => 9,
              5 => 10,
              6 => 11,
              7 => 12,
              10 => 1,
              11 => 2,
              12 => 3,
              13 => 13
          }
              # 9 => 8,
              # 10 => 8,
          plan_items.each_with_index do |item, i|
            sequence = doc_to_sequence_map[i]
            if sequence.present?
                benefit = plan.plan_benefits.find_by(sequence: sequence)
                if item.start_with?("Ded.")
                  item = "Ded & Coin"
                end
                benefit.update(benefit: item)
            elsif i == 8
                carrier_coins = item.sub(/\/.*/, '')
                member_coins = plan_items[(i+1)].sub(/\/.*/, '')
                coins = "#{carrier_coins}/#{member_coins}"
                benefit = plan.plan_benefits.find_by(sequence: 8)
                benefit.update(benefit: coins)
            end
          end
          preventive_care = "100%"
          benefit = plan.plan_benefits.last
          benefit.update(benefit: preventive_care)
      end
    end
  end

  desc "Build Initial Provider Sections"
  # rake seed_tasks:build_provider_sections
  task build_provider_sections: :environment do
    puts "Importing Card Provider/Claims Information"
    default_provider_codes = ["2", "5"]
    needed_codes_mapping = {
        "0": "MedCost VA Plus Network",
        "2": "MedCost",
        "3": "AHA Preferred",
        "5": "Cigna",
        "6": "Cigna (Beam/Stevens)",
        A: "AHA",
        M: "MedCost (smART)",
        T: "MedCost (Tandemloc)"
    }.stringify_keys
    needed_codes = needed_codes_mapping.keys
    vhcs_cp = Vhcs::HlidCardProvider.where(provider_code: needed_codes)
    vhcs_cp.each do |vhcs|
        attributes_hash = vhcs.attributes.except(:provider_code, :group_number)
        attributes_hash.delete_if { |key, value| !key.to_s.include?("_") }

        if default_provider_codes.include?(vhcs.provider_code)
            attributes_hash[:default] = true
        end
        attributes_hash[:title] = needed_codes_mapping[vhcs.provider_code]

        IdCard::ProviderSection.find_or_create_by(attributes_hash)        
    end
    
  end

  desc "Build Initial Rx Sections"
  # rake seed_tasks:build_rx_sections
  task build_rx_sections: :environment do
    puts "Importing Card Rx Information"
    Vhcs::HlrxCrosRef.all.each do |vhcs|
        rx = IdCard::RxSection.find_or_create_by(help_desk: vhcs.help_desk, customer_service: vhcs.customer_service, web_url: vhcs.web_url)
        title = rx.web_url.gsub(/^www\./, '').gsub(/\.com\Z/, '')
        unless title.match?(/\A[A-Z]/)
            title = title.capitalize
        end

        rx.title = title
        rx.save
    end
  end

  desc "Build Initial Network Logos"
  # rake seed_tasks:build_network_logos
  task build_network_logos: :environment do
    puts "Importing Network Logos"
    folder_path = Rails.root.join('seed_docs', 'logo_files', 'network')
    file_names = Dir.children(folder_path)
    default_network_logos = ["CignaLogo.png", "MedCostLogo.png"]

    file_names.each do |logo_upload|
        puts "-- #{logo_upload}"
        file_path = folder_path.join(logo_upload)
        new_logo = ImageProcessorService.new(file_path, "Network").call
        if default_network_logos.include?(logo_upload)
            new_logo.default = true
        end
        new_logo.active = true
        new_logo.save
    end
  end

  desc "Build Initial Employer Logos"
  # rake seed_tasks:build_employer_logos
  task build_employer_logos: :environment do
    puts "Importing Employer Logos"
    folder_path = Rails.root.join('seed_docs', 'logo_files', 'employer')
    file_names = Dir.children(folder_path)

    file_names.each do |logo_upload|
        puts "-- #{logo_upload}"
        file_path = folder_path.join(logo_upload)
        new_logo = ImageProcessorService.new(file_path, "Employer").call
        new_logo.active = true
        new_logo.save
    end
  end

  ## Build Entities Tables

  desc "Build Initial Vendors"
  # rake seed_tasks:build_vendors
  task build_vendors: :environment do
    puts "Importing Vendors"
  end

  desc "Build Initial Carriers"
  # rake seed_tasks:build_carriers
  task build_carriers: :environment do
    puts "Importing Carriers"
  end

  desc "Build Initial Brokers"
  # rake seed_tasks:build_brokers
  task build_brokers: :environment do
    puts "Importing Brokers"
  end

  desc "Build Initial Employers"
  # rake seed_tasks:build_employers
  task build_employers: :environment do
    puts "Importing Employers"
    sql_query = "SELECT PLPlanKey, PlanId, ShortDesc FROM PLPlanHeader WHERE ActiveInactive = 'Active'" # AND PLPlanKey NOT IN ('50','56')"
    plan_headers = VhcsRecord.connection.select_all(sql_query)

    plan_headers.each do |plan_header|
      UpdateEmployerJob.new.perform(employer_plan_header: plan_header, full_sync: true)
    end

  end

  desc "Build Initial Plans"
  # rake seed_tasks:build_plans
  task build_plans: :environment do
    puts "Importing Plans"

    Employer.all.each do |employer|
      puts "-- #{employer.name}"
      UpdateEmployerPlansJob.new.perform(employer.pl_plan_key)
      # employer_plans = employer.id_card_setup.plans

      employer.id_card_setup.plans.each do |plan|
        puts "---- #{plan.title}"
        vhcs_plan_benefits = Vhcs::HlEgglestonCardBenefit.where(plan_id: plan.pb_product_key)
        vhcs_plan_benefits.each do |vpb|
          if vpb.benefit.present?
            benefit = plan.plan_benefits.find_by(sequence: vpb.sequence)
            benefit.update(benefit: vpb.benefit)
          end
        end
      end
      # vhcs_plans = Vhcs::PbProduct.where(company_pb_entity_key: employer.company_pb_entity_key, is_active: 255)
      # vhcs_plans.each do |vp|
      #   plan = employer.id_card_setup.plans.find_by(pb_product_key: vp.pb_product_key)
      #   puts "---- #{plan.title}"
      #   vhcs_plan_benefits = Vhcs::HlEgglestonCardBenefit.where(plan_id: plan.pb_product_key)
      #   vhcs_plan_benefits.each do |vb|
      #       benefit = plan.plan_benefits.find_by(sequence: vb.sequence)
      #       benefit.update(benefit: vb.benefit)
      #   end
      # end
      # if vhcs_plans.empty?
      #   employer.active = false
      # end
      employer.save
    end

  end

  desc "Build Initial Members"
  # rake seed_tasks:build_members
  task build_members: :environment do
    puts "Importing Members"
    Employer.all.map(&:sync_members_with_vhcs)
    Employer.where.missing(:members)
        .update_all(active: false)
  end

  ## Build Employer ID Card Setups

  desc "Determine Initial Card Templates"
  # rake seed_tasks:determine_card_templates
  task determine_card_templates: :environment do
    puts "Updating Card Templates"
    IdCard::Setup.all.each do |setup|
      setup_update_attrs =  case setup.pl_plan_key
                            when "2"
                                {
                                  card_template: "SmartIDCard",
                                  card_color: "white",
                                  rx_title: "FairosRx",
                                  has_divisions: true,
                                  has_dental: true
                                }
                            when "3"
                                {
                                  card_template: "TandemlocIDCard",
                                  card_color: "blue",
                                  rx_title: "FairosRx",
                                  has_dental: true
                                }
                            when "56"
                                {
                                  card_template: "QRCodeIDCard",
                                  card_color: "white",
                                  rx_title: "TheHealthBus"
                                }
                            else
                                {
                                  card_template: "FairosRxIDCard",
                                  card_color: "white",
                                  rx_title: "FairosRx"
                                }
                            end
      rx_title = setup_update_attrs.delete(:rx_title)
      rx_section_id = IdCard::RxSection.find_by(title: rx_title).id
      setup_update_attrs.merge!(rx_section_id: rx_section_id)

      setup.update(setup_update_attrs)
    end

  end

  desc "Determine Initial Network Fields"
  # rake seed_tasks:determine_network_fields
  task determine_network_fields: :environment do
    puts "Updating Network Fields"
    cigna_groups = ["13","20","39","48","49","50","51","53","54","56","58","60","61","62","65","67","68","69"]
    medcost_groups = ["4","5","16","23","33","55","57","59","63","66"]
    old_cigna_groups = ["19","21"]
    smart_medcost = ["2"]
    tan_medcost = ["3"]

    IdCard::Setup.all.each do |setup|
      pl_plan_key = setup.pl_plan_key
      puts pl_plan_key
      setup_update_attrs =  case
                            when cigna_groups.include?(pl_plan_key) || pl_plan_key.blank?
                                { network_provider: "Cigna", network_logo: "CignaLogo.png", provider_section: "Cigna" }
                            when medcost_groups.include?(pl_plan_key)
                                { network_provider: "MedCost", network_logo: "MedcostLogo.png", provider_section: "MedCost" }
                            when old_cigna_groups.include?(pl_plan_key)
                                { network_provider: "Cigna", network_logo: "CignaLogo.png", provider_section: "Cigna (Beam/Stevens)" }
                            when smart_medcost.include?(pl_plan_key)
                                { network_provider: "MedCost", network_logo: "MedcostLogo.png", provider_section: "MedCost (smART)" }
                            when tan_medcost.include?(pl_plan_key)
                                { network_provider: "MedCost", network_logo: "MedcostLogo.png", provider_section: "MedCost (Tandemloc)" }
                            end

      provider_section_title = setup_update_attrs.delete(:provider_section)
      provider_section_id = IdCard::ProviderSection.find_by(title: provider_section_title).id
      setup_update_attrs.merge!(provider_section_id: provider_section_id)

      network_logo_filename = setup_update_attrs.delete(:network_logo)
      network_logo_id = IdCard::NetworkLogo.find_by(filename: network_logo_filename).id
      setup_update_attrs.merge!(network_logo_id: network_logo_id)

      setup.update(setup_update_attrs)
    end
  end

  desc "Determine Initial Employer Fields"
  # rake seed_tasks:determine_employer_fields
  task determine_employer_fields: :environment do
    puts "Updating Employer Fields"
    IdCard::Setup.all.each do |setup|
      setup_update_attrs = {}
      employer_name = Employer.employer_trim_name(setup.employer.name)
      name_segments = employer_name.titleize.split
      name_segments.each do |segment|
          logo = IdCard::EmployerLogo.where("filename LIKE ?", "%#{segment}%")
          if logo&.first
            # setup_update_attrs.merge!(employer_logo_id: logo.first.id)
            setup.employer_logo = logo.first
            break
          end
      end
      json_file_path = Rails.root.join('seed_docs', 'json_files', 'card_exceptions.json')
      file_content = File.read(json_file_path)
      card_exceptions_map = JSON.parse(file_content)
      if card_exceptions_map[setup.pl_plan_key].present?
          setup.field_exceptions.create(card_exceptions_map[setup.pl_plan_key])
      end
      setup.active = setup.employer.active
      setup.save
    end

  end

end
