import json
from typing import Mapping, Any
from io import BytesIO

from backend.condition.condition_trigger_request import ConditionTriggerRequest
from backend.condition.lookups.uprn_lookup_s3 import UprnLookupS3
from backend.condition.processor import process_file
from utils.logger import setup_logger
from utils.s3 import read_io_from_s3


logger = setup_logger()


def handler(event: Mapping[str, Any], context: Any) -> None:

    for record in event.get("Records", []):
        try:
            body_dict = json.loads(record["body"])
            logger.debug("Validating request body")
            payload = ConditionTriggerRequest.model_validate(body_dict)

            logger.debug("Successfully validated request body")

            if payload.uprn_lookup_file_bucket and payload.uprn_lookup_file_key:
                logger.debug("Getting UPRN lookup file from s3")
                uprn_lookup = UprnLookupS3(
                    bucket=payload.uprn_lookup_file_bucket,
                    key=payload.uprn_lookup_file_key,
                )  # TODO: replace with postgres implementation
                logger.debug("Successfully got UPRN lookup file from s3")
            else:
                uprn_lookup = None

            logger.debug("Getting conditions data from s3")
            file_bytes: BytesIO = read_io_from_s3(
                bucket_name=payload.trigger_file_bucket,
                file_key=payload.trigger_file_key,
            )
            logger.debug(
                "Successfully got conditions data from s3. Moving on to process file..."
            )

            process_file(
                file_stream=file_bytes,
                file_type=payload.file_type,
                uprn_lookup=uprn_lookup,
            )

        except Exception as e:
            logger.error(f"Failed to process record: {e}")
