"""secrets.inject — Inject secrets into lambdagent execution context."""
from __future__ import annotations
from agentpaas.db.session import get_db


def inject_secrets(tenant_id: str, environment: str = "production") -> dict:
    """Load secrets for a tenant. Returns dict instead of polluting os.environ.

    SEC-07: Secrets are injected into Context dict, not os.environ,
    so only the current agent can access them.
    """
    db = get_db()
    secrets = {}
    try:
        rows = db.fetchall(
            "SELECT name, encrypted_value FROM secrets WHERE tenant_id=? AND environment=?",
            (tenant_id, environment)
        )
    except Exception as e:
        from agentpaas.observability.logging import logger
        logger.warning("Failed to load secrets for tenant %s: %s", tenant_id, e)
        return secrets

    from .vault import decrypt
    for row in rows:
        name = row["name"].upper()
        try:
            secrets[name] = decrypt(row["encrypted_value"])
        except Exception as e:
            from agentpaas.observability.logging import logger
            logger.error("Failed to decrypt secret %s for tenant %s: %s", name, tenant_id, e)

    return secrets
