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.media_model import MediaSource
    from BowongModalFunctions.models.web_model import SentryTransactionInfo, WebhookNotify, FFMPEGResult
    from BowongModalFunctions.utils.PathUtils import FileUtils
    from BowongModalFunctions.utils.SentryUtils import SentryUtils
    from BowongModalFunctions.utils.VideoUtils import VideoUtils
    import sentry_sdk
    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_bgm_nosie_reduce(media: MediaSource, bgm: MediaSource, noise_sample: Optional[MediaSource] = None,
                                      video_volume: float = 1.4, music_volume: float = 0.1,
                                      sentry_trace: Optional[SentryTransactionInfo] = None,
                                      webhook: Optional[WebhookNotify] = None) -> Tuple[
        FFMPEGResult, Optional[SentryTransactionInfo]]:
        fn_id = current_function_call_id()

        @SentryUtils.sentry_tracker(name="视频混合BGM降噪", op="ffmpeg.bgm.nosie.reduce", 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(video: MediaSource, bgm: MediaSource, func_id: str,
                                 video_volume: float = 1.4, music_volume: float = 0.1,
                                 noise_sample: Optional[MediaSource] = None) -> FFMPEGResult:
            local_input_filepath = f"{s3_mount}/{video.cache_filepath}"
            bgm_filepath = f"{s3_mount}/{bgm.cache_filepath}"
            noise_sample_path = f"{s3_mount}/{noise_sample.cache_filepath}" if noise_sample else None
            temp_audio_path = f"{output_path_prefix}/{config.modal_environment}/bgm_nosie_reduce/outputs/{func_id}/input.wav"
            output_path = f"{output_path_prefix}/{config.modal_environment}/bgm_nosie_reduce/outputs/{func_id}/output.mp4"
            local_output_filepath, metadata = await VideoUtils.ffmpeg_mix_bgm_with_noise_reduce(
                media_path=local_input_filepath,
                bgm_audio_path=bgm_filepath,
                video_volume=video_volume,
                music_volume=music_volume,
                noise_sample_path=noise_sample_path,
                temp_audio_path=temp_audio_path,
                output_path=output_path
            )

            s3_outputs = local_copy_to_s3([local_output_filepath])
            return FFMPEGResult(urn=s3_outputs[0], metadata=metadata,
                                content_length=FileUtils.get_file_size(local_output_filepath), )

        result = await ffmpeg_process(video=media, bgm=bgm, video_volume=video_volume, func_id=fn_id,
                                      music_volume=music_volume, noise_sample=noise_sample)

        if not sentry_trace:
            sentry_trace = SentryTransactionInfo(x_trace_id=sentry_sdk.get_traceparent(),
                                                 x_baggage=sentry_sdk.get_baggage())
        return result, sentry_trace
