from datetime import timedelta

from temporalio import workflow
from temporalio.exceptions import ActivityError

from csirtmu.perun_sync.config import Config
from csirtmu.perun_sync.temporal.activities import PerunSyncActivities

S3_LISTEN_LEEWAY = 10


async def load_s3_data_key(cfg: Config, listen_timeout: int) -> str | None:
    s3_key: str | None = None
    try:
        # We must make sure (via schedule_to_close_timeout) that the activity does not run longer than
        # s3_listen_timeout even in the presence of retries (i.e. due to other errors than Timeout)
        s3_key = await workflow.execute_activity(
            PerunSyncActivities.s3_listen_for_new_object,
            retry_policy=cfg.temporal.retry_policy,
            schedule_to_close_timeout=timedelta(seconds=listen_timeout + S3_LISTEN_LEEWAY),
        )
    except ActivityError as e:
        workflow.logger.warn(e.cause)

    if not s3_key:
        s3_key = await workflow.execute_activity(
            PerunSyncActivities.s3_get_latest_object,
            retry_policy=cfg.temporal.retry_policy,
            start_to_close_timeout=cfg.temporal.activity_timeout,
        )

    if not s3_key:
        workflow.logger.error("No s3 key found")
        return None

    workflow.logger.info(
        "Latest perun propagation found. %s",
        {"propagation_s3_path": f"{cfg.s3.host}/{cfg.s3.bucket}/{s3_key}"},
    )
    return s3_key
