import os
import requests


def upload_files_to_server(api_key, user_email, file_paths, server_url="https://train.banya.ai/upload_user_files_lib/"):

    # Uploads multiple files to a server using a RESTful API.
    #
    # Args:
    #     api_key (str) : Thu user's banya_api_key.
    #     user_email (str): The user's email address.
    #     file_paths (list): A list of strings, where each string is the full path to a file.
    #     server_url (str): The URL of the server's upload endpoint.  Defaults to "https://banya.ai/upload_user_files/".
    #
    # Returns:
    #     dict: A dictionary containing the server's response in JSON format.  Returns None on error.
    #

    try:
        # Prepare the files for uploading
        files = []
        for file_path in file_paths:
            try:
                files.append(('files', (
                os.path.basename(file_path), open(file_path, 'rb'))))  # Preserve the original filename
            except FileNotFoundError:
                print(f"Error: File not found: {file_path}")
                return None  # Or raise the exception, depending on the desired behavior

        # Prepare the data (user_email)
        data = {'user_email': user_email}

        # Send the request
        response = requests.post(server_url, files=files, data=data)  # , verify=False if needed

        # Check the response status code
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)

        # Parse the JSON response
        return response.json()

    except requests.exceptions.RequestException as e:
        print(f"Error during request: {e}")
        return None
    except ValueError as e:
        print(f"Error parsing JSON response: {e}")
        return None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None
    finally:
        # Close the files
        for name, file_tuple in files:
            if isinstance(file_tuple, tuple) and len(file_tuple) > 1:
                file_obj = file_tuple[1]
                if hasattr(file_obj, 'close'):
                    file_obj.close()  # Ensure files are closed after the request


if __name__ == '__main__':
    # Example usage:
    api_key= "aHV4RRFdsDvoZKJL"
    user_email = "tony@nxdf.io"
    file_paths = ["/Users/daib-01/Desktop/data/KakaoTalk_20250206_2025_57_726_group.txt", "/Users/daib-01/Desktop/data/KakaoTalk_20250206_2025_25_525_group.txt"]  # Replace with actual file paths
    server_url = "https://train.banya.ai/upload_user_files_lib/"  #  Keep it here or pass to function

    # Create dummy files for testing
    for file_path in file_paths:
        with open(file_path, "w") as f:
            f.write("This is a test file.")

    response = upload_files_to_server(api_key, user_email, file_paths, server_url)

    if response:
        print("Upload successful!")
        print("Server response:", response)
        # Clean up dummy files
        for file_path in file_paths:
            os.remove(file_path)
    else:
        print("Upload failed.")