"""
Serve sync-node and sync-offer flows.

Uses prefect.serve() - code is already in container, no git clone needed.
Secrets are loaded ONCE at worker startup to avoid Infisical rate limits.
"""
import os

from infisical_sdk import InfisicalSDKClient

# Load secrets from Infisical BEFORE importing flows
# This runs once at worker startup, not per flow run
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,
)

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

# Force internal Prefect API URL for in-cluster flow server registration
os.environ["PREFECT_API_URL"] = "http://prefect-server:4200/api"

# Now import flows (they will see secrets in os.environ)
from prefect import serve

from sync_node import sync_node
from sync_offer import sync_offer


if __name__ == "__main__":
    # Create deployments
    node_deployment = sync_node.to_deployment(
        name="sync-node-deployment",
        tags=["sync", "node", "maps"],
    )
    offer_deployment = sync_offer.to_deployment(
        name="sync-offer-deployment",
        tags=["sync", "offer", "maps"],
    )

    # Serve both flows with concurrency limit
    serve(node_deployment, offer_deployment, limit=4)
