import json
import requests

# --- Configuration ---
def load_config_from_json(file_path="config.json"):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        print(f"Configuration loaded from {file_path}")
        return config
    except FileNotFoundError:
        print(f"Error: Configuration file '{file_path}' not found.")
        exit(1)
    except json.JSONDecodeError:
        print(f"Error: Could not decode JSON from '{file_path}'. Check file format.")
        exit(1)
    except Exception as e:
        print(f"An unexpected error occurred while loading config: {e}")
        exit(1)

# Load configuration at the start
CONFIG = load_config_from_json()
# Access variables from the nested configuration
# Accessing API section
API_CONFIG = CONFIG.get('API', {}) # Use .get() with a default empty dict to prevent KeyError if 'API' is missing
BASE_URL = API_CONFIG.get('BASE_URL')
API_USERNAME = API_CONFIG.get('USERNAME')
API_PASSWORD = API_CONFIG.get('PASSWORD')

def login_api():
    """
    Logs into the API and returns the JWT token.
    Handles potential request errors.
    """
    payload = {
        "username": API_USERNAME,
        "password": API_PASSWORD
    }
    
    headers = {
        "Content-Type": "application/json"
    }

    try:
        response = requests.post(f"{BASE_URL}/auth/login", json=payload, headers=headers)
        response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
        data = response.json()['data']
        jwt = data["token"]
        print("API login successful.")
        return jwt
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error during API login: {e}")
        print(f"Response: {response.text}")
        return None
    except requests.exceptions.ConnectionError as e:
        print(f"Connection Error during API login: {e}")
        return None
    except requests.exceptions.Timeout as e:
        print(f"Timeout Error during API login: {e}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"An unexpected error occurred during API login: {e}")
        return None
    except KeyError:
        print("API response missing 'data' or 'token' key.")
        return None

def add_email_body_to_api(jwt):
    """
    Adds email body data to the API.
    """
    if not jwt:
        print("No JWT token available to add email body.")
        return None

    headers = {
        "Authorization": f"Bearer {jwt}",
        "Content-Type": "application/json"
    }
    try:
        # Assuming this POST request adds new mail records to the database.
        # If it's idempotent (can be called multiple times without issues), it's fine.
        # Otherwise, consider if this should only be called once or based on specific logic.
        response = requests.post(f"{BASE_URL}/report/add-report-mail", headers=headers)
        response.raise_for_status()
        print("Email body successfully added to API.")
        return response
    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error when adding email body: {e}")
        print(f"Response: {response.text}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"An error occurred when adding email body: {e}")
        return None


# --- Main execution logic ---
if __name__ == "__main__":
    jwt_token = login_api()

    if jwt_token:
        # Call add_email_body_to_api only if necessary, e.g., if you're populating the DB
        # For a regular report sending script, you might only need to get_email_bodies_from_api
        add_response = add_email_body_to_api(jwt_token)
    else:
        print("Failed to obtain JWT token. Cannot proceed with email operations.")