package com.idfc.streaming;

import com.amazonaws.services.schemaregistry.serializers.GlueSchemaRegistryKafkaSerializer;
import com.amazonaws.services.schemaregistry.utils.AWSSchemaRegistryConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.idfc.streaming.models.avro.UserEventAvroSource;
import com.idfc.streaming.utils.ConfigHandler;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.Random;

public class KafkaRecordGenerator {

    private static final String TOPIC = ConfigHandler.get("data.sample.user.activity.topic.name");
    private static final String BROKER = ConfigHandler.get("data.bootstrap.servers");
    private static final int MESSAGE_RATE = 100000;
    private static final int DURATION_MINUTES = 15;
    private static final int TOTAL_MESSAGES = 100000;
    private static final Random random = new Random();

    public static ObjectMapper objectMapper = new ObjectMapper();


    public static void main(String[] args) throws Exception {


        Properties properties = new Properties();

        properties.put("bootstrap.servers", ConfigHandler.get("data.bootstrap.servers"));
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, GlueSchemaRegistryKafkaSerializer.class.getName());
        properties.put(AWSSchemaRegistryConstants.DATA_FORMAT, ConfigHandler.get("aws.glue.serializer.source.data.format"));
        properties.put(AWSSchemaRegistryConstants.AWS_REGION, ConfigHandler.get("aws.region"));
        properties.put(AWSSchemaRegistryConstants.SCHEMA_AUTO_REGISTRATION_SETTING,ConfigHandler.getWithDefaultFallBack("aws.glue.schema.auto.registration","true"));
        properties.put(AWSSchemaRegistryConstants.REGISTRY_NAME, ConfigHandler.get("aws.glue.schema.registry.name"));
        properties.put(AWSSchemaRegistryConstants.SCHEMA_NAME, ConfigHandler.get("aws.glue.schema.name"));


        properties.put("security.protocol", "SASL_SSL");
        properties.put("sasl.mechanism", "SCRAM-SHA-512");
        properties.put("sasl.jaas.config", String.format(
                "org.apache.kafka.common.security.scram.ScramLoginModule required " +
                        "username=\"%s\" password=\"%s\";",
                ConfigHandler.get("aws.msk.kafka.user.name"),
                ConfigHandler.get("aws.msk.kafka.password")
        ));



        long startTime = System.currentTimeMillis();
        long endTime = startTime + (DURATION_MINUTES * 60 * 1000);

        KafkaProducer<String, UserEventAvroSource> producer = new KafkaProducer<>(properties);

        int messageCount = 0;
        while (System.currentTimeMillis() < endTime) {
            UserEventAvroSource message =  generateRandomMessage(messageCount++);

            System.out.println(message);

                try  {
                    ProducerRecord<String, UserEventAvroSource> producerRecord = new ProducerRecord<>(TOPIC, "key_" + messageCount, message);
//                        producerRecord.headers().add(new RecordHeader("isSchemaEmbedded", "true".getBytes()));

                producer.send(producerRecord);
                System.out.println("Sent message " + messageCount);
                producer.flush();
                System.out.println("Messages sent successfully.");
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(10);
        }

        producer.close();
    }

    private static UserEventAvroSource generateRandomMessage(int index) throws Exception {
        String[] eventTypes = {"purchase", "view", "login", "logout", "cart_add"};
        String[] deviceTypes = {"mobile", "desktop", "tablet"};
        String[] locations = {"Mumbai", "Delhi", "Bangalore", "Hyderabad", "Chennai"};

        String userId = "user-" + (index % 100);
        String eventType = eventTypes[random.nextInt(eventTypes.length)];
        double amount = random.nextDouble() * 1000;
        String deviceType = deviceTypes[random.nextInt(deviceTypes.length)];
        String location = locations[random.nextInt(locations.length)];

        long currentTime = System.currentTimeMillis();
        int randomValue = random.nextInt(100);

        long timestamp;
        if (randomValue <= 70) {
            timestamp = currentTime;
        } else if (randomValue <= 95) {
            timestamp = currentTime - random.nextInt(10 * 1000);
        } else {
            timestamp = currentTime - (30 * 100) - random.nextInt(30 * 1000);
        }

        String sessionId = "session-" + (index % 50);

        String address = index % 100 == 1 ? null : "address-" + (index % 100);

        return UserEventAvroSource.newBuilder()
        .setUserId(userId)
        .setEventType(eventType)
        .setAmount(amount)
        .setDeviceType(deviceType)
        .setLocation(location)
        .setEventEpoch(timestamp)
        .setSessionId(sessionId)
        .build();
    }
}
