import sys
import os
import json

# 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)
from sdk import CAPIFProviderConnector

capif_sdk_config_path = "./capif-sdk-config-sample.json"

if __name__ == "__main__":
    try:
        # Initialize the connector
        capif_connector = CAPIFProviderConnector(config_file=capif_sdk_config_path)
        capif_connector.onboard_provider()
        print("PROVIDER ONBOARDING COMPLETED")

        # Retrieve AEFs ids and APFs ids to publish an API
        with open(capif_sdk_config_path, 'r') as file:
            config = json.load(file)

        provider_folder = config.get('provider_folder')
        username_folder = config.get('capif_username')
        if not provider_folder:
            raise ValueError("'provider_folder' value is not defined in the configuration file.")

        detailspath = os.path.join(provider_folder, username_folder, "capif_provider_details.json")
        if not os.path.exists(detailspath):
            raise FileNotFoundError(f"The file {detailspath} was not found")

        with open(detailspath, 'r') as file:
            details = json.load(file)

        APF = details.get('APF-1_api_prov_func_id')
        AEF1 = details.get('AEF-1_api_prov_func_id')
        AEF2 = details.get('AEF-2_api_prov_func_id')

        if not APF or not AEF1 or not AEF2:
            raise ValueError("Not all required values were found in 'capif_provider_details.json'")

        # Update the configuration file
        config['publish_req']['publisher_apf_id'] = APF
        config['publish_req']['publisher_aefs_ids'] = [AEF1, AEF2]

        with open(capif_sdk_config_path, 'w') as file:
            json.dump(config, file, indent=4)  # Save JSON with formatting

        print("Configuration file updated successfully.")
        # Reinitialize the connector with the updated configuration
        capif_connector = CAPIFProviderConnector(config_file=capif_sdk_config_path)
        
        capif_connector.publish_services()

    except FileNotFoundError as e:
        print(f"Error: {e}")
    except json.JSONDecodeError as e:
        print(f"Error reading the JSON file: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")