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.enums.models import MediaProtocol
    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 BowongModalFunctions.utils.TimeUtils import TimeDelta
    import sentry_sdk
    from typing import Optional, Tuple
    from modal import current_function_call_id


    @app.function(timeout=1800, 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_frame(media: MediaSource, frame_index: int, seek_time: Optional[TimeDelta] = None,
                                   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.frame", 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, frame_index: int, func_id: str,
                                 seek_time: Optional[TimeDelta] = None) -> FFMPEGResult:
            match media.protocol:
                case MediaProtocol.hls:
                    video_path = f"{media.path}"
                case MediaProtocol.s3:
                    video_path = f"{s3_mount}/{media.cache_filepath}"
                case MediaProtocol.vod:
                    video_path = f"{s3_mount}/{media.cache_filepath}"
                case _:
                    raise NotImplementedError(f"暂不支持此协议")
            output_path = f"{output_path_prefix}/{config.modal_environment}/extract_frame/{func_id}/output.jpg"
            local_output, metadata = await VideoUtils.ffmpeg_extract_frame_image(video_path=video_path,
                                                                                 seek_time=seek_time,
                                                                                 frame_index=frame_index,
                                                                                 output_path=output_path)
            s3_outputs = local_copy_to_s3([local_output])
            return FFMPEGResult(urn=s3_outputs[0], metadata=metadata,
                                content_length=FileUtils.get_file_size(local_output), )

        result = await ffmpeg_process(media=media, frame_index=frame_index, seek_time=seek_time, func_id=fn_id)
        if not sentry_trace:
            sentry_trace = SentryTransactionInfo(x_trace_id=sentry_sdk.get_traceparent(),
                                                 x_baggage=sentry_sdk.get_baggage())
        return result, sentry_trace
