import modal
from dotenv import dotenv_values

fastapi_image = (
    modal.Image
    .debian_slim(python_version="3.11")
    .pip_install_from_pyproject("../pyproject.toml")
    .env(dotenv_values("../.runtime.env"))
    .add_local_python_source('cluster')
    .add_local_python_source('BowongModalFunctions')
    .add_local_python_source("Douyin_TikTok_Download_API", ignore="")
)

app = modal.App(
    name="web_app",
    image=fastapi_image,
    secrets=[
        modal.Secret.from_name('google-secret'),
        modal.Secret.from_name('aws-s3-secret'),
        modal.Secret.from_name('cf-kv-secret'),
    ],
    include_source=False)

with fastapi_image.imports():
    from BowongModalFunctions.api import web_app, web_app_tikhub
    from BowongModalFunctions.config import WorkerConfig

    config = WorkerConfig()

    @app.function(scaledown_window=60,
                  secrets=[
                      modal.Secret.from_name("cf-kv-secret"),
                  ],
                  volumes={
                      config.S3_mount_dir: 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=100)
    @modal.asgi_app()
    def fastapi_webapp():
        return web_app

    # 短保持时间保证IP不停更换
    @app.function(scaledown_window=2,
                  secrets=[
                      modal.Secret.from_name("cf-kv-secret"),
                  ],
                  cloud="aws",
                  volumes={
                      config.S3_mount_dir: 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=100)
    @modal.asgi_app()
    def fastapi_webapp_tikhub():
        return web_app_tikhub
