from typing import Any, Dict, List

from backend.app.config import get_settings
from backend.pashub_fetcher.pashub_client import PashubClient, UnauthorizedError
from backend.pashub_fetcher.pashub_service import PashubService
from backend.pashub_fetcher.pashub_to_ara_trigger_request import PashubToAraTriggerRequest
from backend.pashub_fetcher.token_getter import get_token_from_local_storage
from backend.app.db.models.tasks import SourceEnum
from backend.utils.subtasks import task_handler
from utils.logger import setup_logger
from utils.sharepoint.domna_sharepoint_client import DomnaSharepointClient
from utils.sharepoint.domna_sites import DomnaSites

logger = setup_logger()

S3_BUCKET = "retrofit-energy-assessments-dev"


def get_pashub_client(email: str, password: str) -> PashubClient:
    token = get_token_from_local_storage(email, password)
    logger.info("Token extracted successfully")
    return PashubClient(token=token)


@task_handler(task_source="pashub_fetcher", source=SourceEnum.HUBSPOT_DEAL)
def handler(body: Dict[str, Any], context: Any) -> List[str]:
    logger.info("Received message")

    settings = get_settings()

    pas_hub_email = settings.PASHUB_EMAIL
    pas_hub_password = settings.PASHUB_PASSWORD

    if (not pas_hub_email) or (not pas_hub_password):
        raise ValueError("Pas Hub credentials not provided")

    sharepoint_client = DomnaSharepointClient(
        sharepoint_location=DomnaSites.SOCIAL_HOUSING_WAVE_3
    )

    logger.debug("Validating request body")
    payload = PashubToAraTriggerRequest.model_validate(body)
    logger.debug("Successfully validated request body")

    service = PashubService(
        pashub_client=get_pashub_client(pas_hub_email, pas_hub_password),
        sharepoint_client=sharepoint_client,
        s3_bucket=S3_BUCKET,
    )

    try:
        files: List[str] = service.run(payload)
    except UnauthorizedError:
        logger.warning("Token expired - refreshing")

        service = PashubService(
            pashub_client=get_pashub_client(pas_hub_email, pas_hub_password),
            sharepoint_client=sharepoint_client,
            s3_bucket=S3_BUCKET,
        )

        files = service.run(payload)

    logger.info(f"Saved {len(files)} files")

    return files


if __name__ == "__main__":
    event = {"Records": [{"body": "{}"}]}
    handler(event, None)
