import os
from typing import Optional

from utils.logger import setup_logger

logger = setup_logger()


def build_cloudwatch_log_url(start_ms: Optional[int]) -> str:
    """
    Build a CloudWatch Logs URL for the current Lambda invocation, including a
    timestamp window starting at start_ms. Requires AWS_REGION,
    AWS_LAMBDA_LOG_GROUP_NAME, and AWS_LAMBDA_LOG_STREAM_NAME to be set in the
    environment — i.e. only safe to call inside a Lambda runtime.
    """
    logger.info("Building cloudwatch logs URL")
    region = os.environ["AWS_REGION"]
    log_group = os.environ["AWS_LAMBDA_LOG_GROUP_NAME"]
    log_stream = os.environ["AWS_LAMBDA_LOG_STREAM_NAME"]

    encoded_group = log_group.replace("/", "$252F")
    encoded_stream = log_stream.replace("/", "$252F")

    return (
        f"https://console.aws.amazon.com/cloudwatch/home?"
        f"region={region}"
        f"#logsV2:log-groups/log-group/{encoded_group}"
        f"/log-events/{encoded_stream}"
        f"$3Fstart={start_ms}"
    )
