"""
SecretClient - 从conf-man获取密钥
PM-Agent - 集成conf-man secrets

功能: 通过conf-man HTTP API获取加密存储的密钥
"""
import os
import logging
from typing import Optional
import httpx

logger = logging.getLogger(__name__)


class SecretClient:
    """conf-man密钥HTTP API客户端"""
    
    def __init__(self, api_url: str = None, api_key: str = None):
        self._api_url = api_url or os.environ.get("CONF_MAN_API_URL", "http://localhost:8002")
        self._api_key = api_key or os.environ.get("CONF_MAN_API_KEY", "")
    
    def _request(self, method: str, path: str, **kwargs) -> Optional[dict]:
        """发送HTTP请求"""
        url = f"{self._api_url}{path}"
        headers = {"X-API-Key": self._api_key} if self._api_key else {}
        headers.update(kwargs.pop("headers", {}))
        
        try:
            with httpx.Client(timeout=10) as client:
                response = client.request(method, url, headers=headers, **kwargs)
                if response.status_code < 400:
                    return response.json() if response.text else None
                else:
                    logger.warning(f"API request failed: {response.status_code} {response.text}")
                    return None
        except Exception as e:
            logger.warning(f"Failed to call conf-man API: {e}")
            return None
    
    def get(self, key: str) -> Optional[str]:
        """获取密钥"""
        result = self._request("GET", f"/api/v1/secrets/{key}")
        if result and "value" in result:
            return result["value"]
        return None
    
    def set(self, key: str, value: str) -> bool:
        """设置密钥"""
        result = self._request("POST", "/api/v1/secrets", json={"key": key, "value": value})
        return result is not None
    
    def delete(self, key: str) -> bool:
        """删除密钥"""
        result = self._request("DELETE", f"/api/v1/secrets/{key}")
        return result is not None
    
    def list(self) -> list:
        """列出所有密钥"""
        result = self._request("GET", "/api/v1/secrets")
        if result and isinstance(result, list):
            return [item["key"] for item in result]
        return []
    
    def exists(self, key: str) -> bool:
        """检查密钥是否存在"""
        return self.get(key) is not None


_secret_client: Optional[SecretClient] = None


def get_secret_client() -> SecretClient:
    """获取SecretClient实例"""
    global _secret_client
    if _secret_client is None:
        _secret_client = SecretClient()
    return _secret_client


def get_secret(key: str, fallback: str = None) -> str:
    """获取密钥，如果失败则使用fallback"""
    client = get_secret_client()
    value = client.get(key)
    if value:
        return value
    if fallback:
        logger.warning(f"Using fallback for secret {key}")
        return fallback
    raise ValueError(f"Secret {key} not found and no fallback provided")
