"Get the projects from Bubble and transfer the files to a new S3 location"
import sys

sys.path.append(r".")

import os

import boto3
import requests
from botocore.exceptions import ClientError
from dotenv import load_dotenv

from configs.config import BUBBLE_PRIVATE_KEY
from services.company_profile.company_profile import CompanyProfileMaker
from services.ppt_generator.data_classes.project import Project
from utils.client_check import ClientConfig
from utils.s3_storage import S3BucketStorage

load_dotenv()


class BubbleRetriever:
    "Retrieve the projects from Bubble"

    bubble_url = "https://app.xcapmarket.com/version-test/api/1.1/obj/"
    data = {"Authorization": BUBBLE_PRIVATE_KEY}

    def __init__(self, uid: str = None):
        self.uid = uid
        self.s3 = boto3.client("s3")

    def get_projects(self, uid: str = None):
        "Get the projects from Bubble"
        if uid:
            uid = uid
        elif self.uid:
            uid = self.uid
        else:
            uid = ""

        url = self.bubble_url + "project/" + uid
        r = requests.get(url, data=self.data, timeout=10)

        if uid == "":
            return r.json()["response"]["results"]
        else:
            return [r.json()["response"]]

    def get_project_files(self, project: Project):
        "Get the files for the project"
        project_info = self.get_projects(project.project_id)
        project_files = project_info[0]["provided_files"]
        return project_files

    def store_on_xcm_bucket(
        self, project: Project, file_path: str, client: ClientConfig = None
    ):
        "Store the project on the XCM bucket"
        s3 = S3BucketStorage(os.getenv("xcap_s3_storage"))

        client_name = "xcm"
        if client:
            client_name = client.client

        file_name = os.path.basename(file_path)
        s3_file_path = f"{client_name}/{project.project_id}/{file_name}"

        r = requests.get("https:" + file_path, data=self.data, timeout=10)

        s3.upload_file_to_s3_bucket(
            s3_file_path=s3_file_path,
            s3_file=r.content,
        )
        # create the s3 path for the file

        return s3.s3_file_location

    def is_file_on_s3(self, file_path, bucket_name):
        """
        Check if a file exists in the specified S3 bucket.

        :param file_path: str - The path to the file within the S3 bucket
        :param bucket_name: str - The name of the S3 bucket
        :return: bool - True if the file exists, False otherwise
        """
        try:
            self.s3.head_object(Bucket=bucket_name, Key=file_path)
            return True
        except ClientError as e:
            if e.response["Error"]["Code"] == "404":
                return False
            else:
                raise e  # Re-raise exception if it's not a 404 error


if __name__ == "__main__":
    project = Project.check_project_in_db(project_id="1713555471934x244047193002475520")
    br = BubbleRetriever()
    projects_files = br.get_project_files(project=project)
    for project_file in projects_files:
        br.store_on_xcm_bucket(
            project, project_file, client=ClientConfig("sunbelt").get_client_config()
        )
