import modal

from ..ffmpeg_app import ffmpeg_worker_image, app, config, s3_mount, local_copy_to_s3, output_path_prefix

with ffmpeg_worker_image.imports():
    from BowongModalFunctions.models.cache_tasks.models import MediaSource
    from BowongModalFunctions.models.ffmpeg_tasks.models import SentryTransactionInfo, WebhookNotify, FFMPEGResult
    from BowongModalFunctions.utils.PathUtils import FileUtils
    from BowongModalFunctions.utils.SentryUtils import SentryUtils
    from BowongModalFunctions.utils.VideoUtils import VideoUtils
    from typing import Optional, Tuple
    from modal import current_function_call_id


    @app.function(timeout=600, cloud="aws",
                  max_containers=config.ffmpeg_worker_concurrency,
                  volumes={
                      s3_mount: modal.CloudBucketMount(
                          bucket_name=config.S3_bucket_name,
                          secret=modal.Secret.from_name("aws-s3-secret",
                                                        environment_name=config.modal_environment),
                      ),
                  },
                  )
    @modal.concurrent(max_inputs=1)
    async def ffmpeg_extract_audio(media_source: MediaSource,
                                   sentry_trace: Optional[SentryTransactionInfo] = None,
                                   webhook: Optional[WebhookNotify] = None) -> Tuple[
        FFMPEGResult, Optional[SentryTransactionInfo]]:
        fn_id = current_function_call_id()

        @SentryUtils.sentry_tracker(name="音频提取任务", op="ffmpeg.extract.audio", fn_id=fn_id,
                                    sentry_trace_id=sentry_trace.x_trace_id if sentry_trace else None,
                                    sentry_baggage=sentry_trace.x_baggage if sentry_trace else None)
        @SentryUtils.webhook_handler(webhook=webhook, func_id=fn_id)
        async def ffmpeg_process(media: MediaSource, fn_id: str) -> FFMPEGResult:
            cache_filepath = f"{s3_mount}/{media.cache_filepath}"
            output_path = f"{output_path_prefix}/{config.modal_environment}/extract_audio/outputs/{fn_id}/output.wav"
            output_path, metadata = await VideoUtils.ffmpeg_extract_audio_async(cache_filepath, output_path)
            s3_outputs = local_copy_to_s3([output_path])
            return FFMPEGResult(urn=s3_outputs[0], metadata=metadata,
                                content_length=FileUtils.get_file_size(output_path), )

        result = await ffmpeg_process(media_source, fn_id=fn_id)
        return result, sentry_trace
