import requests
import os
import boto3
import json

# TODO: make the stage configurable to prod or staging
environment = "prod"
STATION_ID = "default"

DEBUG_PRINT = True


def debug_print(message):
    if DEBUG_PRINT:
        print(message)


def get_moderation_auth_token(environment):
    debug_print(f"Getting callback auth token for environment: {environment}")
    secret_arn = os.environ[f"{environment.upper()}_SECRET_ARN"]
    secrets_client = boto3.client("secretsmanager")
    response = secrets_client.get_secret_value(SecretId=secret_arn)
    return response["SecretString"]


moderation_auth_token = get_moderation_auth_token(environment)


def handler(event, context):
    debug_print("Starting Living Radio chat moderation lambda...")
    debug_print(f"Received chat event from Ably: {event}")

    message_text = event["message"]["text"]
    debug_print(f"Received message text: {message_text}")

    moderation_payload = {
        "message": message_text,
    }

    # Send moderation request to studio_api
    try:
        response = requests.post(
            f"https://studio-api.{environment}.suno.com/api/living_radio/{STATION_ID}/moderate-chat-message",
            json=moderation_payload,
            headers={
                "Content-Type": "application/json",
                "Authentication": f"Bearer {moderation_auth_token}",
            },
        )
        response.raise_for_status()
        print(f"Moderation request sent successfully: {response.status_code}")
        print(f"Moderation payload: {json.dumps(moderation_payload)}")

        if response.json().get("is_ok"):
            debug_print("Message is ok. No action needed.")
            action = "accept"
        else:
            debug_print("Message has been blocked.")
            action = "reject"

        return {
            "statusCode": 200,
            "body": {
                "action": action,
            },
        }
    except Exception as e:
        print(f"Error sending moderation request: {str(e)}")
        print(f"Moderation payload was: {json.dumps(moderation_payload)}")
        # Raise an exception here to fail the Lambda execution
        raise e

    return
