import modal
from dotenv import dotenv_values

downloader_image = (
    modal.Image
    .debian_slim(python_version="3.11")
    .apt_install('ffmpeg')
    .pip_install_from_pyproject("../pyproject.toml")
    .add_local_file("../simhei.ttf", "/usr/share/fonts/simhei.ttf", copy=True)
    .run_commands("chmod -R 777 /usr/share/fonts")
    .env(dotenv_values("../.runtime.env"))
    .add_local_python_source('cluster')
    .add_local_python_source('BowongModalFunctions')
)

app = modal.App(
    name="media_app",
    image=downloader_image,
    include_source=False,
    secrets=[
        modal.Secret.from_name("cf-kv-secret"),
    ])

with downloader_image.imports():
    import os, httpx
    import sentry_sdk
    from sentry_sdk.integrations.loguru import LoguruIntegration
    from typing import List
    from loguru import logger

    from BowongModalFunctions.models.settings.cluster import WorkerConfig
    from BowongModalFunctions.utils.KVCache import MediaSourceKVCache, LiveProductKVCache
    from BowongModalFunctions.models.cache_tasks.models import MediaSource

    config = WorkerConfig()

    sentry_sdk.init(dsn="https://85632fdcd62f699c2f88af6ca489e9ec@sentry.bowongai.com/3",
                    send_default_pii=True,
                    traces_sample_rate=1.0,
                    profiles_sample_rate=1.0,
                    add_full_stack=True,
                    shutdown_timeout=2,
                    integrations=[LoguruIntegration()],
                    environment=config.modal_environment,
                    )

    cf_account_id = os.environ.get("CF_ACCOUNT_ID")
    cf_kv_api_token = os.environ.get("CF_KV_API_TOKEN")
    cf_kv_namespace_id = os.environ.get("CF_KV_NAMESPACE_ID")

    modal_kv_cache = MediaSourceKVCache(kv_name=config.modal_kv_name,
                                        environment=config.modal_environment)

    modal_kv_product_cache = LiveProductKVCache(kv_name=config.modal_product_kv_name,
                                                environment=config.modal_environment)


    @sentry_sdk.trace
    def batch_update_cloudflare_kv(caches: List[MediaSource]):
        with httpx.Client() as client:
            try:
                response = client.put(
                    f"https://api.cloudflare.com/client/v4/accounts/{cf_account_id}/storage/kv/namespaces/{cf_kv_namespace_id}/bulk",
                    headers={"Authorization": f"Bearer {cf_kv_api_token}"},
                    json=[
                        {
                            "based64": False,
                            "key": cache.urn,
                            "value": cache.model_dump_json(),
                        }
                        for cache in caches
                    ]
                )
                response.raise_for_status()
            except httpx.RequestError as e:
                logger.error(f"An error occurred while put kv to cloudflare")
                raise e
            except httpx.HTTPStatusError as e:
                logger.error(f"HTTP error occurred while get kv from cloudflare {str(e)}")
                raise e
            except Exception as e:
                logger.error(f"An unexpected error occurred: {str(e)}")
                raise e


    @sentry_sdk.trace
    def batch_remove_cloudflare_kv(caches: List[MediaSource]):
        with httpx.Client() as client:
            try:
                response = client.post(
                    f"https://api.cloudflare.com/client/v4/accounts/{cf_account_id}/storage/kv/namespaces/{cf_kv_namespace_id}/bulk/delete",
                    headers={"Authorization": f"Bearer {cf_kv_api_token}"},
                    json=[cache.urn for cache in caches]
                )
                response.raise_for_status()
            except httpx.RequestError as e:
                logger.error(f"An error occurred while put kv to cloudflare")
                raise e
            except httpx.HTTPStatusError as e:
                logger.error(f"HTTP error occurred while get kv from cloudflare {str(e)}")
                raise e
            except Exception as e:
                logger.error(f"An unexpected error occurred: {str(e)}")
                raise e


    # 导入sub app function
    from .video_apps import *






