"""
Configuration for Prefect flows.
Loads secrets from Infisical using Machine Identity auth.
"""

import os
from infisical_sdk import InfisicalSDKClient


# Load secrets from Infisical before anything else
INFISICAL_API_URL = os.environ["INFISICAL_API_URL"]
INFISICAL_CLIENT_ID = os.environ["INFISICAL_CLIENT_ID"]
INFISICAL_CLIENT_SECRET = os.environ["INFISICAL_CLIENT_SECRET"]
INFISICAL_PROJECT_ID = os.environ["INFISICAL_PROJECT_ID"]
INFISICAL_ENV = os.environ.get("INFISICAL_ENV", "prod")

_client = InfisicalSDKClient(host=INFISICAL_API_URL)
_client.auth.universal_auth.login(
    client_id=INFISICAL_CLIENT_ID,
    client_secret=INFISICAL_CLIENT_SECRET,
)

# Fetch secrets from /prefect and /shared
for _secret_path in ["/prefect", "/shared"]:
    _secrets_response = _client.secrets.list_secrets(
        environment_slug=INFISICAL_ENV,
        secret_path=_secret_path,
        project_id=INFISICAL_PROJECT_ID,
        expand_secret_references=True,
        view_secret_value=True,
    )
    for _secret in _secrets_response.secrets:
        os.environ[_secret.secretKey] = _secret.secretValue
