import modal
from dotenv import dotenv_values

ffmpeg_worker_image = (
    modal.Image.debian_slim(python_version="3.11")
    .apt_install('ffmpeg')
    .pip_install_from_pyproject("../pyproject.toml")
    .env(dotenv_values("../../.runtime.env"))
    .add_local_python_source('cluster')
    .add_local_python_source('BowongModalFunctions')
)

app = modal.App(
    name="ffmpeg_app",
    image=ffmpeg_worker_image,
    include_source=False)

with ffmpeg_worker_image.imports():
    import shutil, backoff, sentry_sdk
    from typing import List
    from loguru import logger
    from BowongModalFunctions.models.settings.cluster import WorkerConfig

    config = WorkerConfig()

    s3_mount = config.S3_mount_dir
    output_path_prefix = config.local_output_mount

    sentry_sdk.init(
        dsn="https://75cca970bfcc3d45d24361e7c0f1833c@sentry.bowongai.com/4",
        send_default_pii=True,
        add_full_stack=True,
        shutdown_timeout=2,
        traces_sample_rate=1.0,
        environment=config.modal_environment,
    )


    @backoff.on_exception(wait_gen=backoff.constant, exception=Exception, max_tries=5, max_time=60,
                          raise_on_giveup=True)
    def local_copy_to_s3(local_outputs: List[str]) -> List[str]:
        s3_outputs = []
        for output in local_outputs:
            out_s3 = output.replace(output_path_prefix, s3_mount)
            out_s3_dir = os.path.dirname(out_s3)
            logger.info(out_s3_dir)
            os.makedirs(out_s3_dir, exist_ok=True)
            shutil.copy(output, out_s3)
            s3_outputs.append(
                out_s3.replace(s3_mount + '/', f"s3://{config.S3_region}/{config.S3_bucket_name}/"))
        return s3_outputs


    # 导入sub app function
    from .ffmpeg_apps import *
