# server.py

import os
import modal
import logging
import requests

env = "dev"

APP_IMAGE = modal.Image.debian_slim().pip_install("requests", "beautifulsoup4")

app = modal.App(f"studio-api-webhook-app-{env}", image=APP_IMAGE)
SECRETS = [
    modal.Secret.from_name("api-callback-token"),
    modal.Secret.from_name("datadog-metrics"),
]

logger = logging.getLogger(__name__)


@app.cls(
    cpu=1.0,
    secrets=SECRETS,
    timeout=240,
    scaledown_window=240,
    retries=modal.Retries(
        max_retries=3,
        backoff_coefficient=2.0,
        initial_delay=5.0,
    ),
    min_containers=1,
    region="us-east",
)
@modal.concurrent(max_inputs=10)
class StudioApiWebhookApp:
    def __init__(self):
        self._callback_token = os.environ["API_CALLBACK_TOKEN"]
        self._headers = {
            "Authentication": f"Bearer {self._callback_token}",
            "X-Auth-Type": "modal",
        }

    @modal.method()
    def callback(self, payload: dict):
        callback_url = payload["callback_url"]
        body = payload["body"]
        if not callback_url:
            logger.error(f"No callback URL found in payload: {payload}")
            return

        try:
            response = requests.post(
                callback_url,
                headers=self._headers,
                json=body,
                timeout=60,  # Add timeout to prevent hanging
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to send webhook callback: {str(e)}")
            # Retry the request
            try:
                response = requests.post(callback_url, headers=self._headers, json=body, timeout=15)
                response.raise_for_status()
                return response.json()
            except requests.exceptions.RequestException as e:
                logger.error(f"Retry failed for webhook callback: {str(e)}")
                return {"error": str(e)}


@app.local_entrypoint()
def main():
    webhook_app = StudioApiWebhookApp()

    # Test creator most common tags
    response = webhook_app.callback.remote(
        {
            "callback_url": "https://studio-api-staging.suno.com/api/profiles/callback/backfill-creator-common-tags",
            "body": {"user_id": "404"},
        }
    )
    print(response)
