import base64
import logging
import json
import boto3
from datetime import datetime, timezone

hook_events = [
    "Hook-Web-Event",
]

HOOKS_PLAY_DURATION_NAME = "HooksPlayDuration"

RECS_EVENTS_KINESIS_CLIENT = boto3.client(
    "kinesis",
    region_name="us-east-2",
)

logger = logging.getLogger(__name__)


def lambda_handler(event, context):
    """
    Lambda handler to check if an event name is in hook_events list and log to RECS_EVENTS_KINESIS stream
    """
    try:
        if "Records" not in event:
            return
        for record in event["Records"]:
            process_record(record)

        return {"statusCode": 200, "body": json.dumps("Success")}
    except Exception as e:
        print(f"Error in lambda_handler: {str(e)}")
        return {"statusCode": 500, "body": json.dumps(f"Error: {str(e)}")}


def process_record(record):
    """
    Process a single record and check if it should be logged to RECS_EVENTS_KINESIS
    """

    if "kinesis" not in record:
        return
    kinesis = record["kinesis"]
    if "data" not in kinesis:
        return

    payload = base64.b64decode(record["kinesis"]["data"])
    json_value = json.loads(payload)
    json_value = json.loads(base64.b64decode(json_value["request_body"]))

    if "event" not in json_value:
        return

    event_name = json_value["event"]
    if event_name not in hook_events:
        return

    properties = json_value["properties"]

    if "context" not in properties:
        return

    event_context = properties["context"]
    hook_id = event_context.get("hookId", "")
    hook_play_duration = event_context.get("playDuration", 0)
    if hook_play_duration == 0:
        logger.info(
            f"Skipping hook play duration event: {hook_id} with play duration 0"
        )
        return
    user_id = properties.get("userId", "")
    timestamp = json_value.get("timestamp", "")
    recs_event = {}
    recs_event["name"] = HOOKS_PLAY_DURATION_NAME
    recs_event["source"] = "web"
    recs_event["user_id"] = user_id
    recs_event["timestamp"] = timestamp
    recs_event["properties"] = {
        "hook_id": hook_id,
        "hook_play_duration": hook_play_duration,
    }

    logger.info(f"Logging hook play duration event: {recs_event}")

    RECS_EVENTS_KINESIS_CLIENT.put_record(
        StreamName="rec-events-stream",
        Data=json.dumps(recs_event),
        PartitionKey=str(datetime.now(timezone.utc).isoformat()),
    )
