import os
import json
from pathlib import Path
from typing import Dict, Optional

class CredentialRegistry:
    """
    Secure registry for managing Neo-Cloud and LLM provider credentials.
    """
    def __init__(self):
        self.config_dir = Path.home() / ".briefcase"
        self.key_file = self.config_dir / "credentials.json"
        self.config_dir.mkdir(exist_ok=True)

    def set_credential(self, provider: str, key: str, value: str):
        creds = self._load()
        if provider not in creds:
            creds[provider] = {}
        creds[provider][key] = value
        self._save(creds)

    def get_credential(self, provider: str, key: str) -> Optional[str]:
        # Priority 1: Environment Variables
        env_key = f"{provider.upper()}_{key.upper()}"
        if env_key in os.environ:
            return os.environ[env_key]
            
        # Priority 2: Registry File
        creds = self._load()
        return creds.get(provider, {}).get(key)

    def _load(self) -> Dict:
        if self.key_file.exists():
            try:
                with open(self.key_file, "r") as f:
                    return json.load(f)
            except Exception:
                return {}
        return {}

    def _save(self, creds: Dict):
        with open(self.key_file, "w") as f:
            json.dump(creds, f, indent=2)

# Singleton access
registry = CredentialRegistry()
