require "json"
require "pg"
#require "protected_attributes"
require "active_record"
require "logging"

#$LOAD_PATH.unshift(File.expand_path('lib', __dir__))

require_relative "../../app_config"

require_relative "./app_config"
require_relative "./s3_manager_mixin"
require_relative "./s3_public_manager_mixin"
require_relative "./module_overrides"
require_relative "./s3_util"
require_relative "./s3_manager"
require_relative "./profanity"
require_relative "../jmep_manager"
require_relative "../models/genre"
require_relative "../models/instrument"
require_relative "../models/jam_track"
require_relative "../models/genre_jam_track"
require_relative "../models/jam_track_track"
require_relative "../models/jam_track_file"
require_relative "../models/jam_track_licensor"
require_relative "./jam_track_lambda_importer"


APP_CONFIG = app_config

# invoked by Lambda
def handler(event:, context:)
  # Extract functionality from your Rake task here
  import_jamtrack(event)
end

module JamRuby

class JamTrackHandlerImporter
    def initialize
      puts "JamTrackHandlerImporter initialized"
    end

    def import_jamtrack(event)
      # Parse job parameters from Amazon S3 batch operations
      invocation_id = event["invocationId"]
      invocation_schema_version = event["invocationSchemaVersion"]

      results = []
      result_code = nil
      result_string = nil

      task = event["tasks"][0]
      task_id = task["taskId"]

      puts("start invocation_id #{invocation_id} task_id #{task_id}")

      puts("TASK #{task}")
      obj_key = URI.unescape(task["s3Key"])
      obj_version_id = task["s3VersionId"]
      bucket_name = task["s3BucketArn"].split(":")[-1]

      puts("Got task: create manifest just for #{obj_version_id} and bucket #{bucket_name} from object #{obj_key}.")

      zip_key = obj_key

      # Configure ActiveRecord connection (update with your DB config)
      ActiveRecord::Base.establish_connection(
        adapter: "postgresql",
        host: ENV["DB_HOST"],
        username: ENV["DB_USER"],
        password: ENV["DB_PASS"],
        database: ENV["DB_NAME"]
        )

        #importer = JamRuby::JamTrackLambdaImporter.new(storage_format="Tency_zipped")
        #importer.dry_run
        JamRuby::JamTrackLambdaImporter.storage_format = "Tency"
        JamRuby::JamTrackLambdaImporter.dry_run
      
        importer
      # add one result to the list of possible acions take n (always 1, for us0)
      results.append(
        {
          "taskId": task_id,
          "resultCode": result_code,
          "resultString": result_string,
        }
      )

  
      {
        "invocationSchemaVersion": invocation_schema_version,
        "treatMissingKeysAs": "PermanentFailure",
        "invocationId": invocation_id,
        "results": results,
      }
    end
  end
end
