import json
import sys
import os
import time
import requests

# Add the SDK directory to PYTHONPATH using a relative path
script_dir = os.path.dirname(os.path.abspath(__file__))  # Current script directory
sdk_path = os.path.join(script_dir, '..', '..', 'sdk')  # Go up two levels and point to 'sdk'
sys.path.insert(0, sdk_path)

# Import necessary classes from the SDK
from sdk import capif_invoker_connector, service_discoverer

# Path to the OpenCAPIF SDK configuration file
capif_sdk_config_path = "./capif_sdk_config_sample.json"

import requests
import json

def update_token(access_token):
    """
    Update the Postman environment with the new access token.
    """
    # Your Postman API Key
    postman_api_key = "PMAK-66fd117ac0a4eb0001e7881b-ecf2b89675a6a1bfd0856838e3b1aa552a"
    
    # Postman Environment ID
    environment_id = "36540500-bfaa8442-180f-4247-892d-b0605581b6a6"
    
    # Postman API URL to modify environments
    url = f"https://api.getpostman.com/environments/{environment_id}"

    # Headers for authentication and content type
    headers = {
        "X-Api-Key": postman_api_key,
        "Content-Type": "application/json"
    }

    # Get the current environment details
    response = requests.get(url, headers=headers)
    
    # Check if the request was successful
    if response.status_code == 200:
        environment_data = response.json()

        # Check if the variable already exists
        variables = environment_data['environment']['values']
        variable_found = False
        for var in variables:
            if var['key'] == "ACCESS TOKEN":
                
                # Update both initial and current value
                var['value'] = access_token  # Set initial value
                var['current_value'] = access_token  # Set current value
                variable_found = True
                break
        
        if not variable_found:
            # If the variable doesn't exist, append it
            variables.append({
                "key": "ACCESS TOKEN",
                "value": access_token,  # Initial value
                "current_value": access_token,  # Current value
                "enabled": True
            })

        # Send the PUT request to update the environment
        updated_data = {
            "environment": {
                "name": environment_data['environment']['name'],
                "values": variables
            }
        }

        # Update the environment in Postman
        put_response = requests.put(url, headers=headers, data=json.dumps(updated_data))
        
        if put_response.status_code == 200:
            print("Access token updated successfully.")
        else:
            print(f"Error updating the variable: {put_response.status_code}")
    else:
        print(f"Error getting the environment: {response.status_code}")


if __name__ == "__main__":
    # Initialize the CAPIF invoker
    capif_connector = capif_invoker_connector(config_file=capif_sdk_config_path)
    capif_connector.onboard_invoker()
    print("INVOKER ONBOARDING COMPLETED")
    # Now, with the certificates available, proceed with discovery
    discoverer = service_discoverer(config_file=capif_sdk_config_path)
    discoverer.discover()
    while True:
        discoverer.get_tokens()
        
        details = discoverer.invoker_capif_details
        tamaño = len(details["registered_security_contexes"])
        ip = details["registered_security_contexes"][tamaño-1]["aef_profiles"][0]["ip"]
        port = details["registered_security_contexes"][tamaño-1]["aef_profiles"][0]["port"]
        discoverer.check_authentication["ip"] = ip
        discoverer.check_authentication["port"] = port
        discoverer.check_authentication()

        # Load API details from the JSON file
        token = discoverer.token

        # Update the Postman token with the retrieved access token
        update_token(token)

        print(token)

        # Wait for 599 seconds before the next update
        time.sleep(599)
